Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the visibility property with javascript

I tested the visibility of the following div:

<div id="div1">div</div>

with the style defined separately

#div1 {
    visibility:visible; //or hidden
}

If the style is defined inline as <div id="div1" style="visibility:visible">div</div> there it's easy to check the visibility in the element.style.visibility property. But the problem is when the style is defined separately (as shown above - #div1, .div1 or div).

And so where can one check the visibility property using only pure javascript? jQuery returns correct style everytime (I dunno how to track it), so how did they do it? Here is one fiddle with my unsuccesful attempts, no tests except jQuery's work:

alert($(el).css('visibility')); // jQuery works well - returns correct property
alert(el.style.visibility); // not works - always empty string
alert(el.offsetWidth > 0 || el.offsetHeight > 0 ? 'yes':'no'); // also not working - always true - http://stackoverflow.com/questions/1343237/how-to-check-elements-visibility-via-javascript
alert(el.getComputedStyle); // undefined - http://stackoverflow.com/questions/4795473/check-visibility-of-an-object-with-javascript
alert(el.getAttribute('visibility')); // not works - of course null

Any ideas on how to succeed? Tested in latest Firefox 15.

like image 809
Stano Avatar asked Dec 27 '22 20:12

Stano


2 Answers

getComputedStyle is a global method. Use it as follows:

window.getComputedStyle(el, null).getPropertyValue('visibility');
like image 188
Rob W Avatar answered Dec 29 '22 10:12

Rob W


You are using getComputedStyle wrong:

getComputedStyle( el ).visibility
//"visible"

Demo: http://jsfiddle.net/hMFry/1/

In internet explorer you would use:

el.currentStyle.visibility;
like image 20
Esailija Avatar answered Dec 29 '22 08:12

Esailija