views:

539

answers:

4

Preface: I have jQuery and jQuery UI included on a page.

I have this function defined:

    function swap(sel) {
        if (1 == 1) {
           $(sel).hide('drop',{direction:'left'});
        }
    }

How do I fix the (1 == 1) part to test to see if the element is already hidden and then bring it back if it is. I'm sure this is easy, but I'm new to jQuery.

+2  A: 

Why you don't use toggle() ?

For example:

function swap(sel) {
  $(sel).toggle();
}
CMS
+2  A: 

Perhaps $(sel).toggle(); is what you are looking for? That is the best way to toggle an element's visibility.

Andrew Hare
+2  A: 

As the other answerers have said, toggle() is the best solution. However if for some reason you can't/don't want to use toggle, and if your selector is for only one element:

function swap(sel) {
    if ($(sel).is(':visible')) {  // Is this element visible?
       $(sel).hide('drop',{direction:'left'});
    }
}

Caveat: The :visible check will return a false positive if the element or any of its parents are :hidden. If that's important to you, you might want to check out this solution which attempts to check for any of that, as well.

Adam Bellaire
Would toggle do the effect though?
tyndall
AFAIK, the only toggle effects are the default, which is to fade in and grow at the same time, and slideToggle, which slides the content down from no height to full height. The speed can be configured just like any jQuery animation. If you don't want either of those, you have to animate manually.
Adam Bellaire
thanks for this. good info to know.
tyndall
+3  A: 

if you don't like toggle, then this may help you:

function swap(sel) {
  if($(sel).is(':visible')) {
    $(sel).hide('drop',{direction:'left'});
  } else {
    $(sel).show('drop',{direction:'left'});
  }
}
Ionut Staicu
I like the is(':visible'). Quite slick.
tyndall