CodeBlanks Logo Icon CodeBlanks

IntersectionObserver

JavaScript course · Advanced · Lesson 91/100

Learn to lazy-load by observing when an element enters the viewport with IntersectionObserver.

IntersectionObserver

IntersectionObserver watches how an element intersects the viewport. You get notified when an element enters or leaves the screen. The best known use is lazy loading: loading images only when they approach the viewport.

You create it with new IntersectionObserver(callback, options). The callback receives an entries array on every intersection change. The observe method picks which element to watch.

Options: root, rootMargin, threshold

The second argument is an options object with three fields:

  • root: the ancestor used as the viewport; defaults to the browser viewport
  • rootMargin: a margin around the root, in CSS margin syntax
  • threshold: how much intersection triggers the callback; a number 0 to 1 or an array

If you omit it, defaults apply: full viewport, zero margin, threshold 0.

Callback and entry

The callback receives an entries array and the observer itself. Each IntersectionObserverEntry describes one element's current state. The most useful fields:

  • isIntersecting: is the element intersecting right now?
  • target: the watched element itself
  • intersectionRatio: how much of it is visible (0-1)

When you watch many elements they all arrive in the same array; tell them apart with target.

Exercise Catch the img in the viewport

Create an IntersectionObserver. The callback takes an entries array; for each entry, if isIntersecting is true, log entry.target. Set threshold to 0 and start with observe(img).

Show example solution
1. Create with new IntersectionObserver((entries) => {...}).
2. For each entry, if isIntersecting, log entry.target.
3. Set { threshold: 0 } and start with observer.observe(img).

Example solution:
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      console.log(entry.target);
    }
  }
}, { threshold: 0 });
observer.observe(img);

Test yourself

  1. What is the most common use of IntersectionObserver?

    • Loading images when they enter the viewport
    • Counting button clicks
    • Computing array length
    • Changing color values
    Show answer

    Loading images when they enter the viewport — Correct. Lazy loading is the most common use; the image loads only when visible.

  2. Set the threshold to 50%

    const io = new IntersectionObserver(callback, { threshold:____});
    Show answer
    const io = new IntersectionObserver(callback, { threshold:0.5});
  3. Match entry fields

    isIntersecting
    Visible right now?
    target
    Watched element
    intersectionRatio
    Visible ratio
    root
    Intersection ancestor

All lessons in Advanced