How it works
Try to scroll or resize the container below, or scroll or resize the browser window, or zoom in and out the page.
Explanation
There are four IntersectionObserver instances created for every target element, one for each side of the element.
Their boundaries are spread from the viewport edges to the observed element's edges slightly overlapping the element.
Once the element's position change is detected, it starts a request animation frame loop.
When the element's bounding rectangle stops changing, the request animation frame loop stops.
If the change affected one dimension, only one observer will be recreated.
If the element moved vertically up or down the "top" and "bottom" observers are recreated,
if the movement was horizontal the "left" and "right" pair of observers are recreated.
In case of diagonal movement, all observers are recreated.
- It doesn't run anything in the background when an observed element's bounding box doesn't change.
- It doesn't listen to scroll or resize events.
Why four observers?
It guarantees that movement of an observed element in any direction will be detected,
even if it is partly overlapped by its parent scrollable container, making this approach reliable and quirks-free.
The limitation is when an observed element is fully scrolled out of view.