views:

490

answers:

4

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?

+9  A: 

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.

Ant P.
Good idea. It's even specified: http://www.w3.org/TR/cssom-view/#offset-attributes
porneL
+1  A: 

Using Prototype:

if($('someDiv').visible) {...}
Diodeus
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.
Chris MacDonald
I only use the library. I didn't write it.
Diodeus
A: 

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.

EoghanM
+1 for MochiKit - I loves MK.
Jason Bunting
A: 

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.

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?
Ben Blank