Test if the image I am about to grab using code is visible to the user or not
Limitations:
-
Plain javascript – please do not suggest jQuery or other framework
-
I am only interested in
display:noneandvisibility:hiddenbut opacity and such is of course welcome
Code: below (taken from here) does not work in my DEMO
Question: Can you help making either work or suggest a better script?
Version A
function isVisible(obj){
if (obj == document) return true;
if (!obj) return false;
if (!obj.parentNode) return false;
if (obj.style) {
if (obj.style.display == 'none' || obj.style.visibility == 'hidden') return false;
}
else if (window.getComputedStyle) { // MY BAD - I PUT THE INCORRECT ELSE HERE
var style = window.getComputedStyle(obj, "");
if (style.display == 'none' || style.visibility == 'hidden') return false;
}
else if (obj.currentStyle) {
var style = obj.currentStyle;
if (style['display'] == 'none' || style['visibility'] == 'hidden') return false;
}
return isVisible(obj.parentNode);
}
Version B
function isVisible1(obj) {
var cnode = obj;
try {
while(cnode) {
if (cnode.nodeName) {
if (cnode.nodeName.toLowerCase()=="body") {
return true;
}
}
if (cnode.style.display=="none" || cnode.style.visibility=="hidden") {
return false;
}
cnode = cnode.parentNode;
}
return true;
}
catch(ex) {return false;}
}
Try taking the computed style conditionals outside the else of the style check. We want to check both the inline styles and the computed styles (from stylesheets.)
Changing:
To:
Forked fiddle: http://jsfiddle.net/MXgbh/1/