Search code examples
javascriptdomvisibility

How do I check if an element is really visible with JavaScript?


In JavaScript, how would you check if an element is actually visible?

I don't just mean checking the visibility and display attributes. I mean, checking that the element is not

  • visibility: hidden or display: none
  • underneath another element
  • scrolled off the edge of the screen

For technical reasons I can't include any scripts. I can however use Prototype as it is on the page already.


Solution

  • For the point 2.

    I see that no one has suggested to use document.elementFromPoint(x,y), to me it is the fastest way to test if an element is nested or hidden by another. You can pass the offsets of the targetted element to the function.

    Here's PPK test page on elementFromPoint.

    From MDN's documentation:

    The elementFromPoint() method—available on both the Document and ShadowRoot objects—returns the topmost Element at the specified coordinates (relative to the viewport).