Observing Element Visibility
Create an observer and watch elements.
Why Intersection Observer?
Traditionally, detecting when an element enters the viewport meant listening to scroll and calling getBoundingClientRect constantly, which is slow and janky.
The Intersection Observer API watches visibility efficiently and asynchronously, off the main thread.
Creating an Observer
You create an observer with new IntersectionObserver(callback). The callback runs whenever a watched element's visibility crosses a threshold.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
console.log(entry.target, entry.isIntersecting);
});
});All lessons in this course
- Observing Element Visibility
- Lazy Loading Images
- Infinite Scrolling
- Scroll-Triggered Animations