The above solution caters for this "invisibility" scenario:
display:none;
but it does not cater for this one:
visibility: hidden;
In order to include the test for visibility: hidden; the script can be modified as follows...
First, create a cross browser compliant function to get the desired element's computed style:
computedStyle = function(vElement) {
return window.getComputedStyle?
?window.getComputedStyle(vElement,null)
:vElement.currentStyle; //IE 8 and less
}
Second, create the function to test for visibility
isVisible = function(vElement) {
return !(vElement.offsetWidth == 0 && vElement.offsetHeight == 0)
&& computedStyle(vElement).visibility != "hidden";
}
Finally, simply reference the isVisible function wherever needed as follows:
if (isVisible(myElement)) {
alert('You can see me!');
} else {
alert('I am invisible ha ha!');
}
Just a note that the current isVisible() tests do not cater for a number of "invisibility" scenarios (however the tests could I suppose be enhanced to include these). Here are a few examples:
- where an element is the same colour as the surrounding colour
- where an element is visible but physically behind another element eg. different z-index values
It is also probably worth noting the following regarding the above computedStyle() function:
- It can of course be used for many other style related purposes besides testing visibility
- I have opted to ignore :pseudo style testing due to patchy browser support, however with a minor modification to the function this could be included if desired.