What is the Intersection Observer API
· Category: HTML & CSS
Short answer
Intersection Observer asynchronously watches for changes in the visibility of a target element relative to the viewport or a root element.
Steps
- Create an observer with
new IntersectionObserver(callback, options). - Call
observer.observe(targetElement). - In the callback, check
entry.isIntersectingto trigger behavior.
Example
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
});
document.querySelectorAll('.fade-in').forEach((el) => observer.observe(el));
Tips
- Ideal for lazy loading images and infinite scroll.
- More performant than scroll event listeners.
- Set
rootMarginto trigger slightly before the element is visible.