- Source:
Members
(static) VisibilityObserver
A class offering extended visibility information about elements in regard to their positioning to the viewport (bounds). An intersection observer is nice and concise, but if you want to build scroll-based effects or control lazy loading a little bit more in detail, you are out of luck, since the intersection observer does not offer much to help you in these cases.
The VisibilityObserver offers tailor-fit information to build visibility-based effects, such as "pixels visible", "percent scrolled" or "distance in viewports". Additionally, the VisibilityObserver handles edge-cases like elements, which are bigger than the viewport itself, which results in intersections not being recognized is bounds are not visible.
This class aims to do the heavy lifting using an IntersectionObservers, to keep CPU usage down, but cover the edge cases, if needed, with polling and precise calculations. Features, that are not achievable with intersections alone, are very likely opt-in features.
In case there is no native IntersectionObserver available, this implementation falls back to a SimplePollingObserver, which replaces the IntersectionObserver and brute-forces the functionality with CPU-intensive polling. This should be avoided if possible, but guarantees interoperability with older ES5 environments.
This class roughly follows the interface defined by things like MutationObserver and IntersectionObserver.
See class documentation below for details.
Example
(new VisibilityObserver(100, 30))
.observe(element1, false, true)
.observe(element2, true, true)
.observe(element4, true, true)
.observe(element5)
.unobserve(element5)
;
element1.addEventListener(
'visiblepixels.visibilityobserver',
e => { console.log(`${e.detail} vertical pixels of element1 are visible`); }
);