- IntersectionObserver
- Last updated on
new IntersectionObserver()
The IntersectionObserver object can be used to observe an element and run a callback function when it enters or leaves the viewport (or another element).
It’s far more performant than older approaches that use scroll event listeners and the Element.getBoundingClientRect() method.
You can use the new IntersectionObserver() constructor to create a new IntersectionObserver object.
Pass in a callback function as an argument. The callback accepts two arguments: entries, an array of the elements that caused the callback function to run, and optionally the observer itself.
// Create a new IntersectionObserver object
let observer = new IntersectionObserver(function (entries, observer) {
console.log('An intersection happened!');
console.log(entries);
});
After creating an observer, use the IntersectionObserver.prototype.observe() method to observe an element. Whenever the observed element enters or leaves the viewport, the callback function will run.
// The element to observe
let app = document.querySelector('#app');
// Observe the #app element
observer.observe(app);
Try it! Log each heading when it enters or leaves the viewport.