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?
views:
48070answers:
5$(element).css('display')=='none' The functions dont work with visibility attribute
You can use the "hidden" and "visible" selectors.
$(element:hidden)
http://docs.jquery.com/Selectors/hidden
$(element:visible)
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'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>
}
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.