2

Is there a way to check if a DOM element is really visible on screen?

Meaning :

  • Its not hidden (e.g: display: none, visibility: hidden)
  • Its not hidden by another element
  • its opacity is not 0, neither is the opacity of one of its parents.

(these are the cases i could think of)

this is what i got so far

function isVisible(el) {
    //is hidden (display, visibility)
    var isHidden = el.style.display == 'none' || ['collapse', 'hidden'].indexOf(el.style.visibility) == -1;
    if(isHidden)
        return false;

    //is hidden by another element
    el.scrollIntoView();
    var rect = el.getBoundingClientRect();
    var targetAtPos = document.elementFromPoint(rect.left, rect.top);
    var isHiddenByAnother = targetAtPos != el;
    if(isHiddenByAnother)
        return false;

    //Check opacity
}
Youssef
  • 1,033
  • 8
  • 16

1 Answers1

0

Many of these checks are done by the pretty new (e.g. yet not supported by Safari as of March 10, 2023) el.checkVisibility(). That covers display: none, visibility: hidden, visibility: collapse, opacity: 0 and lots of other edge cases that you and me would probably forget.

This does, however, to my knowledge, not check whether the element is hidden behind another element or outside the viewport. So this is where you could use your elementFromPoint technique.

Matteo B.
  • 3,906
  • 2
  • 29
  • 43