Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?
(The question regards Firefox)
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?
(The question regards Firefox)
Now most browsers support getBoundingClientRect method, which has become the best practice. Using an old answer is very slow, not accurate and has several bugs.
The solution selected as correct is almost never precise. You can read more about its bugs.
This solution was tested on IE7+, iOS5+ Safari, Android2+, Blackberry, Opera Mobile, and IE Mobile 10.
How to use:
You can be sure that the function given above returns correct answer at the moment of time when it is called, but what about tracking element's visibility as an event?
Place the following code at the bottom of your
<body>
tag:If you do any DOM modifications, they can change your element's visibility of course.
Guidelines and common pitfalls:
Maybe you need to track page zoom / mobile device pinch? jQuery should handle zoom/pinch cross browser, otherwise first or second link should help you.
If you modify DOM, it can affect the element's visibility. You should take control over that and call
handler()
manually. Unfortunately, we have no cross browseronrepaint
event. On the other hand that allows us to make optimizations and perform re-check only on DOM modifications that can change element's visibility.Never Ever use it inside jQuery $(document).ready() only, because there is no warranty CSS has been applied in this moment. Your code can work locally with your CSS on hard drive, but once put on remote server it will fail.
After
DOMContentLoaded
is fired, styles are applied, but the images are not loaded yet. So, we should addwindow.onload
event listener.We can't catch zoom/pinch event yet.
The last resort could be the following code:
You can use awesome feature pageVisibiliy HTML5 API if you care if the tab with your web page is active and visible.
TODO: this method does not handle two situations:
z-index
using
overflow-scroll
in element's containertry something new https://pawelgrzybek.com/the-intersection-observer-api-explained/
I use this function (it only checks if the y is inscreen since most of the time the x is not needed)
Here's my solution, it will work if an element is hidden inside a scroll-able container.
Here's a demo (try re-sizing the window to)
I only needed to check if it's visible in the Y axis (for a scrolling ajax load more records feature).
my shorter and faster version.
add jsFiddle as required https://jsfiddle.net/on1g619L/1/
For a similar challenge i really enjoyed this gist which exposes a polyfill for scrollIntoViewIfNeeded().
All the necessary Kung Fu needed to answer is within this block:
this
refers to the element that you want to know if it is i.e.overTop
oroverBottom
- just should get the drift...There is jQuery plugin called inview that does the job