SyntaxStudy
Sign Up
HTML Intersection Observer API
HTML Intermediate 4 min read

Intersection Observer API

Intersection Observer

Intersection Observer efficiently detects when elements enter or leave the viewport — ideal for lazy loading images and scroll-triggered animations.

Example
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add("visible");
      // Load lazy image
      const img = entry.target;
      if (img.dataset.src) {
        img.src = img.dataset.src;
        observer.unobserve(img);
      }
    }
  });
}, { threshold: 0.1 });

document.querySelectorAll(".lazy").forEach(el => observer.observe(el));
Pro Tip

Use threshold: 0.1 to trigger when 10% of the element is visible.