Monday, July 12, 2010

Check if an element is truly hidden with jQuery

I’m tinkering with a web application and have a situation where I want to select only elements which are visible on the page. Initially I tried using the is(“:visible”) jQuery (v1.4.2) selector, but it seems to be broken, at least for IE.

My solution was inspired by an old posting, and I created the following extension which checks the styles on the current element, and if it’s inherited, then check the parent element.

$.extend(
$.expr[":"],
{
reallyhidden: function (a) {
var obj = $(a);
while ((obj.css("visibility") == "inherit" && obj.css("display") != "none") && obj.parent()) {
obj = obj.parent();
}
return (obj.css("visibility") == "hidden" || obj.css('display') == 'none');
}
}
);

and use it like this:

if (element.is(':reallyhidden')) return false;