Matthew
Matthew

Reputation: 15632

jquery toggle slideUp/slideDown

I've got a div#items and if it's clicked then div#choices slideDown(). If it's clicked again then div#choices should slideUp(); How can I test if choices is down or up already? I know I could store in a variable and toggle it's value whenever div#items is clicked, but what if #choices has been slid down by other means?

Upvotes: 9

Views: 21270

Answers (3)

Rohit Suthar
Rohit Suthar

Reputation: 3628

Try this -


HTML:

<a href="#demo" class="nav-toggle">Show</a>
<div id="demo" style="display:none;">
<p>short info</p>
</div>


JQUERY SCRIPT:

$('.nav-toggle').click(function(){
   var content_id = $(this).attr('href');               
   var toggle_switch = $(this); 
     $(content_id).toggle(function(){
    if($(this).css('display')=='none'){
          toggle_switch.html('Show');
    }else{
      toggle_switch.html('Hide');
        }
    });  
});

Upvotes: 0

Andy E
Andy E

Reputation: 344517

As Marimuthu's answer points out, you can use slideToggle() to slide up if the div is already open, or down if it's closed.

You can also check the display property to find out if it's currently visible or not. From the jQuery docs for slideUp().

Once the height reaches 0, the display style property is set to none to ensure that the element no longer affects the layout of the page.

Knowing this, you can check to see if it is set to "none":

var $choices = $('div#choices');
if ($choices.css("display") == "none")
    $choices.slideDown();
else
    $choices.slideUp();

Upvotes: 7

Marimuthu Madasamy
Marimuthu Madasamy

Reputation: 13531

Use .slideToggle()

Upvotes: 15

Related Questions