Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.6 — Observers
JavaScript · Example 1 of 3

IntersectionObserver inside a scrolling box

Round 1 is the starting report for every box. After scrolling, only the boxes whose state changed are reported. Scroll the grey box yourself and watch the colours.

Observers let the browser tell you when something changes instead of you checking again and again: IntersectionObserver reports when elements enter or leave view, ResizeObserver when an element's size changes, and MutationObserver when the DOM itself is changed.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write onceVisible(el, fn) that calls fn() the first time el becomes visible, then stops observing.

02

Use a MutationObserver to log New message: <text> whenever an <li> is added to #chat, then add one with code.

Explain it without notes

01

Why are observers better than scroll and resize listeners for visibility and size checks?

02

How would you lazy-load images with IntersectionObserver? What do rootMargin and threshold do?

03

What does MutationObserver report, and when does its callback run?

04

When would you use ResizeObserver instead of CSS container queries?

IntersectionObserver inside a scrolling box

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

round 1: Box 0 in
round 1: Box 1 in
round 1: Box 2 out
round 1: Box 3 out
round 1: Box 4 out
round 1: Box 5 out
round 2: Box 0 out
round 2: Box 1 out
round 2: Box 3 in
round 2: Box 4 in