View Full Version : Is Element Visible
INeedADip
10-10-2006, 01:30 PM
I would love a function that determines if an element is visible.
Something that would traverse the elements parents to see if their style properties (display, visible, etc..) are visible.
How are others solving this? Is there a "trick" or does everyone recursively check all parent elements?
INeedADip
10-10-2006, 02:54 PM
Well..this is working for me now. Just thought I would post it.
function isVisible(el){
el = YAHOO.util.Dom.get(el);
var region = YAHOO.util.Dom.getRegion(el);
if(isNaN(region.top) || isNaN(region.right) || isNaN(region.top) || isNaN(region.left))
return false;
var func = function(o){
if(o.tagName.toUpperCase() == "BODY") return true;
if(YAHOO.util.Dom.getStyle(o, 'visibility') == 'hidden') return false;
if(YAHOO.util.Dom.getStyle(o, 'display') == 'none') return false;
if(!o.parentNode || o.parentNode == null) return true;
return func(o.parentNode);
}
return func(el);
}
jack.slocum
10-10-2006, 03:20 PM
The Element object has a function isVisible() but it only checks the elements visibility/display. I will add an optional param isVisible(deep) which will be a boolean value of whether to walk the dom to determine if a parentNode is hidden.
Great suggestion - thanks.
Jack
Animal
10-11-2006, 03:43 AM
What about if other elements in the DOM tree (not necessarily in the ancestors axis) are CSS-positioned over the element with a higher z-index?
The element could be "visible" in the CSS sense, but might be occluded.
That would require going through the whole document, checking for higher z-indexes, and testing whether each element covers the element in question (with 100% opacity, and non-transparent background).
jack.slocum
10-11-2006, 07:39 AM
Here's what I went with:
isVisible : function(deep) {
var vis = YAHOO.util.Dom.getStyle(this.dom, 'visibility') != 'hidden'
&& YAHOO.util.Dom.getStyle(this.dom, 'display') != 'none';
if(!deep || !vis){
return vis;
}
var p = this.dom.parentNode;
while(p && p.tagName.toLowerCase() != 'body'){
if(YAHOO.util.Dom.getStyle(p, 'visibility') == 'hidden' ||
YAHOO.util.Dom.getStyle(p, 'display') == 'none'){
return false;
}
p = p.parentNode;
}
return true;
}
I switched the recursive function call to a while loop for performance reasons.
jack.slocum
10-11-2006, 07:41 AM
Animal, that would be nice but I'm sure it would be slow as hell. If you want to mess around with it, I wouldn't be adverse to adding it as a third param, "checkOverlays" or something.
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.