Is this element visible?
Nicholas Stimpson
Posted on July 13, 2019
The sample couldn't be much simpler. The question is, is the div element containing the text "Hello World" visible or hidden?
Visible right? Well maybe. jQuery begs to differ!
The problem lies is jQuery's (and widely copied) definition and implementation of its check for visibility. The definition is
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
The implementation is
!! (el.offsetWidth || el.offsetHeight || el.getClientRects().length)
The div in question has a CSS property display value of "contents", which means that it creates no layout box of its own. Its child elements' layout boxes are instead directly connected to its parent layout box. The CSSOM specifications say that offsetWidth, offsetHeight and getClientRects().length must all return zero for such an element
For both offsetWidth and offsetHeight If the element does not have any associated CSS layout box return zero and terminate this algorithm.
for getClientRects() If the element on which it was invoked does not have an associated layout box return an empty DOMRectList object and stop this algorithm.
So in the light of this, what should be done? The intuitive answer clearly doesn't tally with the technical details. And it's not clear to me from a developer perspective whether an element with no layout box really should be considered visible, just because its contents are. Yet from a user perspective it seems obvious that it should. Do we need a third state beyond "visible" and "hidden"?
Posted on July 13, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.