This is not to be confused with "How to tell if a DOM element is visible?"
I want to determine if a given DOM element is visible on the page.
E.g. if the element is a child of a parent which has display:none;
set, then it won't be visible.
(This has nothing to do with whether the element is in the viewport or not)
I could iterate through each parent of the element, checking the display
style, but I'd like to know if there is a more direct way?
-
From a quick test in Firefox, it looks like the size and position properties (clientWidth, offsetTop etc.) all return 0 when an element is hidden by a parent being
display:none
.porneL : Good idea. It's even specified: http://www.w3.org/TR/cssom-view/#offset-attributes -
Using Prototype:
if($('someDiv').visible) {...}
Chris MacDonald : It would have been more helpful if you had provided the source code for this function of Prototype, to show how it could actually be done.Diodeus : I only use the library. I didn't write it. -
As I'm using MochiKit, what I came up with based on Ant P's answer was:
getElementPosition('mydiv').y != 0
I can also check whether it's in the viewport (vertically) by:
y = getElementPosition('mydiv').y (y < getViewportPosition().y + getViewportDimensions().h && getViewportPosition().y < y)
Incidentally this also works in IE6.
Jason Bunting : +1 for MochiKit - I loves MK. -
Relying on the position being 0 is brittle. You're better off writing a helper function to iterate through the parents to check their display style directly.
Ben Blank : Care to elaborate? If it's in the standard, supported by the standards-compliant crowd (FF, WebKit, …), and supported by the non-compliant gorilla, what makes it brittle?
0 comments:
Post a Comment