en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Error description with element hidden check in "Element size and scrolling"

Open 0xtoorich opened this issue 5 years ago • 4 comments

The tutorial said:

Geometry properties are calculated only for displayed elements.

If an element (or any of its ancestors) has display:none or is not in the document, then all geometry properties are zero (or null for offsetParent).

For example, offsetParent is null, and offsetWidth, offsetHeight are 0 when we created an element, but haven’t inserted it into the document yet, or it (or it’s ancestor) has display:none.

We can use this to check if an element is hidden, like this:

function isHidden(elem) {
  return !elem.offsetWidth && !elem.offsetHeight;
}

But, what if the hidden element is hidden by setting the width to 0, not the height? 😀

0xtoorich avatar Jun 10 '20 05:06 0xtoorich

@chanjsq try it?

iliakan avatar Jun 10 '20 07:06 iliakan

image

Look above, my test code.

0xtoorich avatar Jun 10 '20 14:06 0xtoorich

Guess, you're right, we can make || instead of && there.

iliakan avatar Jun 10 '20 14:06 iliakan

What about this?

function isHidden(elem) {
  return !elem.offsetWidth && (!elem.offsetHeight || !elem.offsetWidth);
}

0xtoorich avatar Jun 10 '20 14:06 0xtoorich