how to detect if div is hidden by javascript -
i have div, hidden, , in case don't want google adds appear/are loaded @ inside div.
what best practice make such check javascript?
you should @ computed style of node want, via window.getcomputedstyle
, rather style attribute of node, css elsewhere may effecting too.
checking whether node covered node more difficult, 1 way use document.elementfrompoint
find out node top-most @ specific point, node should until you're satisfied it's visible. example, check centre of node node.
function ishidden(node, checkifcovered) { var absposition = function absposition(node) { var x = 0, y = 0, h = node.offsetheight || 0, w = node.offsetwidth || 0; { node.offsetleft && (x = x + node.offsetleft); node.offsettop && (y = y + node.offsettop); } while (node = node.offsetparent); return {x: x, y: y, h: h, w: w}; }, o, style; if (checkifcovered && document.elementfrompoint) { // if supported o = absposition(node); // position & size o.centre = {x: o.x + o.w / 2, y: o.y + o.h / 2}; // centre of node if (document.elementfrompoint(o.centre.x, o.centre.y) !== node) { return true; // node in centre => covered } } { // loop on parent nodes if (node.nodetype === 9) break; // skip #document style = window.getcomputedstyle(node); if ( style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0' ) { return true; } } while (node = node.parentnode); // passed tests, not hidden return false; }
example usage
ishidden(document.getelementbyid('mydivid')); // true->hidden ishidden(document.getelementbyid('mydivid'), true); // true->hidden or covered
further things consider
- is node located possible scroll view? see fabrizio calderan's comment.
- now edited in. parent nodes hidden? may want loop dom tree find out. it's okay if covered though, obviously. see loïc faure-lacroix's comment.
Comments
Post a Comment