Bluedayz
Bluedayz

Reputation: 599

jQuery: How to display and hide elements alternately with a sliding motion?

I have one button and if the button is clicked, a text should .slideDown(). If the button is clicked again, the text should .slideUp().

HTML

<div id="button">CLICK ME!</div>
<div id="text" style="display:none;">
    Example Text
</div>

jQuery

$('#button').on('click', function() {
    $('#text').slideDown();
    $('#button').addClass('button-clicked');
});
$('#button.button-clicked').on('click', function() {
    $('#text').slideUp();
    $('#button').removeClass('button-clicked');
});

Is there a more simple solution?

Upvotes: 0

Views: 338

Answers (3)

dsgriffin
dsgriffin

Reputation: 68596

There's no need for all that - just use slideToggle() instead:

$("#button").click(function() {
   $("#text").slideToggle();
   $(this).text(function(i, text){
       return text === "Up" ? "Down" : "Up";
   });
});

jsFiddle here.

Upvotes: 4

Russell Zahniser
Russell Zahniser

Reputation: 16364

Every time you do .click(), you are attaching a new event handler. So by the time the button has been clicked twice, there are two event handlers that fire every time you click it, one sliding down and one sliding up.

If you need the id of the button to change each time you click it, do something like this:

$("#button").click(function() {
  $("#text").slideToggle();
  $(this).attr("id", $(this).attr("id") == "button" ? "button-clicked" : "button");
});

The click handler stays attached to that button element even though the ID is changing.

If the id change is just triggering a different appearance through CSS, a more conventional approach would be to do $(this).toggleClass("clicked"), and then define the clicked state in #button.clicked.

Upvotes: 1

just use slideToggle()

$("#button").click(function() {
   $("#text").slideToggle(); //will handle slides  automatically
});

Upvotes: 3

Related Questions