Intersection Observer — Web Animation

IntersectionObserver creates an observer (a watcher) that calls your callback when an observe()d element crosses the edge of an area. Write new…

In the scroll-driven animation lesson, the room cards fade out again when you scroll back up, because their timeline runs backwards too. If a card only needs to appear once and then stay, you need IntersectionObserver. IntersectionObserver is an API built into the browser that creates an observer (a watcher). The observer tells you when an element enters an area or leaves it. The area can be the screen, or a scroller.

An observer works like a guard at the gate of a housing estate who notes every guest passing through. You don't have to look out of the window every second. The guard calls you when someone comes in or goes out. In the code, the guard is the observer, the guests are elements, and the gate is the edge of the area. The phone call is the callback: a function you give to the observer, which the browser calls.

Creating an observer

This code makes each room card (.room) appear once, when that card enters the screen:

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {                    // this card is inside the area
      entry.target.classList.add('animate-from-bottom');
      observer.unobserve(entry.target);            // once is enough, stop watching
    }
  }
}, { root: null, threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

document.querySelectorAll('.room').forEach((el) => observer.observe(el));
.room {
  opacity: 0;
  transform: translateY(16px);
  transition: opacity 300ms ease-out, transform 300ms ease-out;
}
.room.animate-from-bottom { opacity: 1; transform: none; }

The first callback comes right away

Take a guess first: you call observer.observe() on three room cards. All three are still far below and not visible at all. Before you scroll even a little, how many times is the callback called?

We watched Mrs. Sri's three cards (120 px tall) inside a 300 px tall scroller. This is what the callback received as soon as observe() was called, before any scrolling:

Card isIntersecting intersectionRatio Distance from the top of the area
Terrace Room false 0 410 px
Attic Room false 0 540 px
Garden Room false 0 670 px

The answer is once. That one callback carries three entries, all isIntersecting: false. The same in Chromium 147, WebKit 26.4 and Firefox 146. The browser always reports each element's starting state. That's why if (entry.isIntersecting) is a must. Without that check, all three cards appear right away, before they're visible.

Three options: root, threshold, rootMargin

The second argument of new IntersectionObserver is an object with three options (settings):

Measured with threshold: 0.5, scrolling down until each card had passed:

Card When the "in" callback came When the "out" callback came
Terrace Room isIntersecting: true, ratio 0.54 false, ratio 0.46
Attic Room true, ratio 0.50 false, ratio 0.29
Garden Room true, ratio 0.67 false, ratio 0.33

Look at the "out" column. With a threshold of 0.5, the Terrace Room card is still 46% visible, but it is already reported as isIntersecting: false. So in the three browsers we tested, isIntersecting follows the threshold, not simply whether some part is visible.

rootMargin: '0px 0px -50px 0px' cuts 50 px off the bottom of the area. In that 300 px scroller, the Terrace Room card was reported in only when its top edge reached 236 px from the top, not 300 px (the bottom edge of the scroller). Lazy loading images (loading an image when it is about to be visible) uses the opposite: '200px 0px' grows the area, so the callback is called 200 px before the image is visible.

There is a newer option, scrollMargin (Chrome 120, Firefox 141, Safari 26). It widens the area of a scroller inside the root, such as a horizontal carousel (a row of cards you move sideways). In Chromium 156, a card hidden 100 px past the right edge of a carousel counted as inside with scrollMargin: '200px', but not with rootMargin: '200px'.

In the exercise, you build this options object: createObserverConfig(0.1, "0px 0px -50px 0px") prints {"root":null,"threshold":0.1,"rootMargin":"0px 0px -50px 0px"}.

Appearing once, one after another

Call unobserve(entry.target) after the class is added, so that each card appears once. We scrolled down past the three cards. During that scroll, with unobserve, there were only 3 callbacks (one per card). Without unobserve, there were 6: each card was reported when it came in, and once more when it left at the top.

You can pick the animation class from the direction of motion. The class name says where the card comes from, not where it moves: a card that moves up ("up") comes from below, so its class is animate-from-bottom:

Direction of motion Class The card comes from
"up" animate-from-bottom below
"down" animate-from-top above
"left" animate-from-right the right
"right" animate-from-left the left
anything else animate-fade no shift, only a fade

On Mrs. Sri's page, the room cards appear one after another, 60 ms apart. Appearing in turn like this is called a stagger. Card number i (from 0) gets a delay of i × 60 ms. In the exercise, you write a function for these delays: createStaggerDelays(3, 60) = [0, 60, 120]. Each number is set as that card's transition delay, for example el.style.transitionDelay = '60ms' for the second card. The first card doesn't wait.

Why not a scroll listener?

Another way is a scroll listener, which is called on every scroll event and checks the card's position itself. We scrolled that 300 px scroller by 1,000 px in 40 steps:

Called Where
addEventListener('scroll', ...) 40 times the main thread, every event
IntersectionObserver, threshold 0.5 6 times (3 with unobserve) only when a threshold is crossed

The numbers were the same in all three browsers. Real scrolling sends one scroll event per frame, up to 120 a second on a 120 Hz screen. A listener usually calls getBoundingClientRect() (it reads the element's position and size) on every event, and that call can force the browser to compute layout. IntersectionObserver computes where the element and the area overlap inside the browser, and only calls the callback when something changed.

IntersectionObserver or view()?

Here it is compared with view() from the scroll-driven animation lesson:

IntersectionObserver animation-timeline: view()
Appears once, then stays forward and back with the scroll
Length time (300 ms) scroll distance
JavaScript a small callback, once per card none
Support Chrome 51, Firefox 55, Safari 12.1 Chrome 115, Safari 26, Firefox 159
Other uses lazy loading, infinite scroll animation only

A third choice is still experimental: CSS timeline-trigger (Chrome 146, not yet in Firefox or Safari). This property starts an animation once when an element enters the screen, with no JavaScript.

Reduce motion

For "Reduce motion", the observer code doesn't change. CSS decides: drop the movement and keep a 150 ms fade. Drop the stagger too:

@media (prefers-reduced-motion: reduce) {
  .room { transform: none; transition: opacity 150ms linear; }
}
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
el.style.transitionDelay = reduce ? '0ms' : delays[i] + 'ms';

In that JavaScript, delays is the result of createStaggerDelays and i is the card's number.

🤔 rootMargin inside an iframe

When your page runs in an iframe from another origin, like the Playground, and its root is null, rootMargin is ignored. In all three browsers, with a 300 px tall iframe and rootMargin: '0px 0px -100px 0px', the area should end at 200 px. But a card at 250 px was still reported in. With root: document or a scroller as the root, rootMargin applies.

⚠️ Why do the cards appear early, or not at all?

TL;DR: IntersectionObserver creates an observer (a watcher) that calls your callback when an observe()d element crosses the edge of an area. Write new IntersectionObserver(callback, { root, threshold, rootMargin }). In the options, root = the area (the screen when null, or a scroller), threshold = how much of the element must be visible (0.5 = when 50% is visible), rootMargin = the area grown or shrunk ('0px 0px -50px 0px', a unit is required). The first callback comes right away for every element, even those not visible yet (isIntersecting: false). So always check entry.isIntersecting (inside or not), add the animation class, then unobserve(entry.target) (stop watching) so the element appears once. The class name says where the element comes from: one that moves "up" comes from below, so animate-from-bottom. With a stagger (elements appearing in turn), element i gets a delay of i × 60 ms. Against a scroll listener: 6 callbacks against 40 events for the same scroll. Against view(): the element appears once and every browser supports it, but it needs a little JavaScript. With "Reduce motion", CSS drops the movement and keeps a 150 ms fade, and the stagger delay becomes 0.

⚡ A guard at the gate

Write:

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {                    // this card is inside the area
      entry.target.classList.add('animate-from-bottom');
      observer.unobserve(entry.target);            // once is enough, stop watching
    }
  }
}, { root: null, threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

document.querySelectorAll('.room').forEach((el) => observer.observe(el));

Meaning: IntersectionObserver creates an observer (a watcher), like a guard at a gate: the browser tells you when a .room card enters or leaves the screen (root: null). The callback (the function in the first argument) receives one entry (a report) per card. When entry.isIntersecting is true, the card is inside: its class is added, then unobserve stops watching that card. The animation is still a CSS transition.

⚡ The first callback comes right away

Guess first: you observe() three room cards, all far below and not visible yet. Before you scroll even a little, how many times is the callback called?

Once, with three entries at the same time, all isIntersecting: false. The browser always reports each element's starting state.

Meaning: That's why if (entry.isIntersecting) is a must in the callback. Without that check, all three cards appear before they're visible.

⚡ threshold and rootMargin

Meaning: threshold is how much of the element must be visible, from 0 to 1. threshold: 0.5 means the callback is called when 50% of the element is visible. rootMargin grows or shrinks the area. You write it like a CSS margin, and it must have a unit, px or %.

⚡ Appearing once only

Meaning: unobserve(entry.target) makes the observer stop watching a card that has appeared. So each card appears once. Scrolling past three cards gives 3 callbacks, not 6 (without unobserve, a card is reported again when it leaves). A scroll listener on the same scroll is called 40 times, on the main thread.

What you will learn