BillyBib BillyBib - 4 months ago 11
Javascript Question

jQuery button click only working once

I'm trying to use jQuery to hide and show elements on a button click. I have the following code:

$(function(){
$('#link-form').hide()
$('#link-submit').hide()

$('#main-header-submit').on("click", function() {
$('#link-form').show();
$('#main-yield').fadeTo("fast", 0.2)
$(this).on("click", function() {
$('#link-form').hide()
$('#main-yield').fadeTo("fast", 1)
})
})
})


This successfully shows and hides the divs when I click the
'main-header-submit'
button, but when I click the button (effectively for a third time) to make the elements show again nothing happens. Any help much appreciated.

Answer

If you rewrite your code like this, it should work:

$(function(){
  $('#main-header-submit').on("click", function() {
    $('#link-form').toggle("fast");
  })
})

The toggle function hides the elements if they are shown and shows them if they are hidden. Check here http://api.jquery.com/toggle/

Comments