tags:

views:

48070

answers:

5

In jQuery, suppose you have an element of some kind that you're hiding and showing, using .hide(), .show() or .toggle(). How do you test to see if that element is currently hidden or visible on the screen?

+6  A: 

$(element).css('display')=='none' The functions dont work with visibility attribute

Mote
I can't get this to work properly, but I'll bow out of this one.
Will
This only checks for the display property of a single element. The :visible attribute checks also the visibility of the parent elements.
chiborg
+32  A: 

You can use the "hidden" and "visible" selectors.

$(element:hidden)

http://docs.jquery.com/Selectors/hidden

$(element:visible)

http://docs.jquery.com/Selectors/visible

twernt
works perfect, thank you
Umair
+181  A: 

As, the question refers to a single element, this code might be more suitable:

$(element).is(":visible")

Same as twernt suggestion, but applied to single element.

Tsvetomir Tsonev
+7  A: 

Tsvetomir's solution worked for me, couldn't post a comment though. Expanding on it...

if(  $(element).is(":visible") == "true" ){
  // do something
}
else{
  // do something else<br>
}
Hedley Lamarr
Doesn't work. The expression returns Boolean.
Daud
Apologies... if ($(element).is(":visible") == true)
Hedley Lamarr
if the code $(element).is(":visible") returns a Boolean value, then the check '== true' is completely unnecessary.
jlech
`"true"` is string, not boolean
takeshin
+2  A: 

If you already have a reference to a particular element and you want to perform some action on it only if it is visible, or only if it is hidden then you can do do the following. This basically allows you to do the following, but without the 'if' statement :

if ($(button).is(":visible")) {
     $(button).animate({ width: "toggle" });   // hide button
 }

Here's how to do it without the 'if' :

var button = $('#btnUpdate')[0];

if (weWantToHideTheButton) 
    {
        // hide button by sliding to left
        $(button).filter(":visible").animate({ width: "toggle" });
    }
    else {
        // show button by sliding to right
        $(button).filter(":hidden").animate({ width: "toggle" });
    }

This uses the same :visible or :hidden check, but acts on a specific element we already have previously selected (the variable button).

In this case I wanted to do this, but in only one line.

Simon_Weaver