Question

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.

Was it helpful?

Solution

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'});
  }
}

OTHER TIPS

Why you don't use toggle() ?

For example:

function swap(sel) {
  $(sel).toggle();
} 

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top