Skip to main content

Intersection Observer API (Live Playground)

The Intersection Observer API is a modern, performant way to detect when elements become visible or hidden within the viewport. This is useful for implementing features like lazy loading, infinite scrolling, or showing animations when elements come into view.

Creating an Intersection Observer

To create an intersection observer, you need to pass a callback function and an optional options object to the IntersectionObserver constructor. The callback function is called whenever an observed element's visibility changes. The options object can include properties like root, rootMargin, and threshold to customize the observer's behavior.

const options = {
root: null,
rootMargin: '0px',
threshold: 0.5,
};

const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
console.log('Element visibility changed:', entry);
});
}, options);

Observing Elements

Use the observe() method of the intersection observer to start observing an element.

const elementToObserve = document.querySelector('.my-element');
observer.observe(elementToObserve);

Handling Element Visibility Changes

In the callback function, you can access information about the observed element using the IntersectionObserverEntry object, which includes properties like isIntersecting, intersectionRatio, and target.

const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is visible:', entry.target);
} else {
console.log('Element is hidden:', entry.target);
}
});
}, options);

Stopping Observation

To stop observing an element, use the unobserve() method of the intersection observer.

observer.unobserve(elementToObserve);

Disconnecting the Observer

To stop observing all elements and disconnect the observer, use the disconnect() method.

observer.disconnect();

Now you know how to use the Intersection Observer API to efficiently detect when elements become visible or hidden in the viewport. This powerful feature can help you create more efficient and interactive web applications.

Live Playground, Try it Yourself