Reputation: 14280
I have a weird issue in my case.
I have something that is hidden but jquery can't find it.
html
<div id='test'>
<h3>title here</h3>
</div>
css
#test h3 {
visibility: hidden;
}
js
if (('#test h3').is(':visible')) {
alert('visible');
}
I am not supposed to get alert box because my h3 tag is hidden but the alert box keep popping up. Can anyone help me this weird issue? Thanks a lot!
Upvotes: 0
Views: 170
Reputation: 220116
Since hiding the visibility still consumes space, jQuery considers them visible.
Here's a quote from the docs:
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
Elements with
visibility:hidden
oropacity: 0
are considered visible, since they still consume space in the layout.
If you want to check if the element's visibillity
is not set to hidden
, use this:
if ( $('#test h3').css('visibility') == 'visible' ) {
alert('visible');
}
To check for ancestors too, use this:
var visible = true;
$('#test h3').parents().addBack().each(function() {
if ( $.css(this, 'visibility') != 'visible' ) return visible = false;
});
if ( visible ) {
// do whatever...
}
You can abstract all that into a reusable filter expression:
jQuery.expr[':']['visible-real'] = function(el) {
var visible = true;
$(el).parents().addBack().each(function () {
if ( $.css(this, 'visibility') != 'visible' ) return visible = false;
});
return visible;
};
You can then use it whenever you need it as follows:
if ( $('#test h3').is(':visible-real') ) {
alert('visible');
}
Here's the fiddle: http://jsfiddle.net/3LGm7/
Upvotes: 5