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

  1. Create an observer with new IntersectionObserver(callback, options).
  2. Call observer.observe(targetElement).
  3. In the callback, check entry.isIntersecting to 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 rootMargin to trigger slightly before the element is visible.