IntersectionObserver
Published by Brayan K
IntersectionObserver is a browser API that efficiently watches when an element scrolls into or out of view, running a callback only when its visibility crosses a threshold you set.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Observe geometry changes instead of reading every scroll event
IntersectionObserver reports asynchronous geometry observations relative to a root. The callback also receives an initial observation after a target is registered, so the introduction’s threshold description is not a promise that every callback follows a user scroll. Layout changes, root movement and target movement can all matter.
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
const states = [];
let finish;
const completed = new Promise(resolve => { finish = resolve; });
// The scroll container is the root; the page viewport is not the root here.
const observer = new window.IntersectionObserver(entries => {
for (const entry of entries) {
states.push(entry.isIntersecting);
if (!entry.isIntersecting) root.scrollTop = 200;
else finish();
}
}, { root, threshold: 0.5 });
try {
observer.observe(target);
await completed;
console.log(states.join(", "));
} finally { observer.disconnect(); root.remove(); }
// ✅ Expected output:
// false, trueThe example waits for actual observer callbacks rather than sleeping for a guessed duration. The first target is outside the 100-pixel scroll root, then becomes fully inside it. The browser computes intersections asynchronously; do not expect the callback to have run immediately after observe. DOM Manipulation owns element selection and updates.
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
root.scrollTop = 200;
let resolveEntry;
const first = new Promise(resolve => { resolveEntry = resolve; });
const observer = new window.IntersectionObserver(entries => resolveEntry(entries[0]), { root });
observer.observe(target);
console.log("registered");
const entry = await first;
console.log(entry.target === target, entry.isIntersecting);
observer.disconnect();
root.remove();
// ✅ Expected output:
// registered
// true trueChoose the root, margin and threshold for different purposes
const observer = new window.IntersectionObserver(() => {}, {
rootMargin: "10px 20px",
threshold: [1, 0, 0.5]
});
console.log(observer.root === null);
console.log(observer.rootMargin);
console.log(JSON.stringify(observer.thresholds));
observer.disconnect();
// ✅ Expected output:
// true
// 10px 20px 10px 20px
// [0,0.5,1]A null root uses the viewport. rootMargin expands or shrinks the root’s intersection rectangle; threshold selects target-area ratios whose crossing can trigger an observation. A threshold of 0.5 is half the target’s area, not half the viewport height. Percentage margins are resolved from the root rectangle’s width, so do not treat a vertical percentage margin as a percentage of root height.
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
spacer.style.height = "140px";
async function initial(margin) {
return new Promise(resolve => {
const observer = new window.IntersectionObserver(entries => {
observer.disconnect();
resolve(entries[0].isIntersecting);
}, { root, rootMargin: margin });
observer.observe(target);
});
}
console.log(await initial("0px"));
console.log(await initial("0px 0px 60px 0px"));
root.remove();
// ✅ Expected output:
// false
// truenew window.IntersectionObserver(() => {}, { threshold: 1.5 });
// ✅ Expected error:
// RangeError: Failed to construct 'IntersectionObserver': Threshold values must be numbers between 0 and 1A margin can provide a prefetch lead distance, but it does not guarantee that content will finish loading before use. A threshold is not a polling frequency or a guaranteed frame-by-frame stream of positions. Use the entry’s target to associate each result with its element.
Geometric intersection does not establish human visibility
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
root.scrollTop = 200;
target.style.opacity = "0";
const result = await new Promise(resolve => {
const observer = new window.IntersectionObserver(entries => {
observer.disconnect();
resolve(entries[0].isIntersecting);
}, { root, threshold: 0.5 });
observer.observe(target);
});
console.log(result, getComputedStyle(target).opacity);
root.remove();
// ✅ Expected output:
// true 0The ordinary observer does not prove an element is unobscured, opaque, attended to or read. isIntersecting can also be true at an edge contact with a zero ratio; a policy that needs a substantial positive area should check its chosen ratio and positive dimensions explicitly. Do not equate this API alone with an advertising viewability or user-attention measurement.
Experimental visibility-tracking options have additional support and performance constraints. This lesson uses the widely supported geometry model only; no claim is made about those options or ad-impression compliance.
An observer can track many targets, and cleanup has a scope
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
const second = document.createElement("div");
second.style.height = "40px";
tail.before(second);
const seen = new Map();
let finish;
const completed = new Promise(resolve => { finish = resolve; });
const observer = new window.IntersectionObserver(entries => {
for (const entry of entries) seen.set(entry.target, entry.isIntersecting);
if (seen.has(target) && seen.has(second)) finish();
}, { root });
observer.observe(target);
observer.observe(second);
await completed;
console.log(seen.size, seen.get(target), seen.get(second));
observer.disconnect();
root.remove();
// ✅ Expected output:
// 2 false falseA callback receives a batch. Keep per-target state rather than treating entries[0] as the only element that matters. unobserve removes one target; disconnect stops all observations for that observer. A disconnected observer can be used again, but a component’s own disposed state should still be terminal if that is its documented lifecycle.
takeRecords drains entries already queued for that observer; it does not force a new layout measurement or synchronously answer “is this visible now?” The brief uses a lifetime flag as well as disconnect so an already-captured callback cannot update disposed state. JavaScript Memory Management & Garbage Collection owns broader resource cleanup.
Guided exercise: choose a target-area threshold
Complete the literal hints. This example inspects the observer configuration; it does not claim that constructing an observer starts watching any element.
const observer = new window.___(() => {}, { threshold: ___ }); // 👉 replace ___ with IntersectionObserver
// 👉 replace ___ with 0.5
console.log(JSON.stringify(observer.thresholds));
observer.___(); // 👉 replace ___ with disconnect
// ✅ Expected output:
// [0.5]Brief: record each target once after half its area intersects
Implement onceInView(root, targets). Accept a mounted, positive-size HTMLElement root and a dense array of at most twenty unique positive-size HTMLElement descendants from the same document. Reject the root itself and invalid or duplicate targets before creating the observer. Snapshot the selected targets.
Observe with this root and a half-area threshold. Mark a selected target only when isIntersecting is true, its ratio is at least 0.5 and its recorded width/height are positive. Unobserve it after the first accepted entry. seen() returns a fresh array of marked element references in original selection order.
dispose is terminal and idempotent: disconnect and ignore later callbacks while preserving the already-recorded history. Ignore unknown and duplicate callback entries. This records geometry once; it does not load a resource or establish human attention.
function onceInView(root, targets) {
if (!(root instanceof HTMLElement) || !root.isConnected || root.clientWidth <= 0 || root.clientHeight <= 0) {
throw new TypeError("root must be a mounted positive-size element");
}
if (!Array.isArray(targets) || targets.length > 20) throw new TypeError("invalid target list");
const selected = [], unique = new Set();
for (let i = 0; i < targets.length; i++) {
const target = targets[i];
if (!Object.hasOwn(targets, i) || !(target instanceof HTMLElement) ||
target.ownerDocument !== root.ownerDocument || target === root || !root.contains(target) ||
unique.has(target)) throw new TypeError("invalid target");
const box = target.getBoundingClientRect();
if (box.width <= 0 || box.height <= 0) throw new TypeError("target must have positive size");
unique.add(target);
selected.push(target);
}
const seen = new Set();
let active = true;
const observer = new window.IntersectionObserver(entries => {
if (!active) return;
for (const entry of entries) {
if (!unique.has(entry.target) || seen.has(entry.target)) continue;
if (entry.isIntersecting && entry.intersectionRatio >= 0.5 &&
entry.boundingClientRect.width > 0 && entry.boundingClientRect.height > 0) {
seen.add(entry.target);
observer.unobserve(entry.target);
}
}
}, { root, threshold: [0, 0.5] });
selected.forEach(target => observer.observe(target));
return Object.freeze({
seen() { return selected.filter(target => seen.has(target)); },
dispose() {
if (!active) return;
active = false;
observer.disconnect();
}
});
}
const root = document.createElement("div");
root.style.cssText = "width:120px;height:100px;overflow:auto;position:relative;border:0;padding:0";
const spacer = document.createElement("div");
spacer.style.height = "200px";
const target = document.createElement("div");
target.style.cssText = "height:40px;background:teal";
target.textContent = "Target";
const tail = document.createElement("div");
tail.style.height = "100px";
root.append(spacer, target, tail);
document.getElementById("app").append(root);
const selected = [target];
const tracking = onceInView(root, selected);
selected.length = 0;
root.scrollTop = 200;
await new Promise(resolve => {
function check() {
if (tracking.seen().length === 1) resolve();
else requestAnimationFrame(check);
}
check();
});
console.log(tracking.seen()[0] === target, tracking.seen() === tracking.seen());
tracking.dispose();
tracking.dispose();
console.log(tracking.seen().length);
root.remove();
// ✅ Expected output:
// true false
// 1
Practice quiz
What does this complete program print? const observer=new window.IntersectionObserver(()=>{});console.log(observer.root===null);observer.disconnect();
- true
- false
- undefined
- TypeError
Answer: true. The default root is the viewport, represented by null.
What does threshold: 0.5 describe?
- Half the viewport height
- Half the target’s intersection area ratio
- A callback every half second
- A 50-pixel margin
Answer: Half the target’s intersection area ratio. The ratio compares intersected area with target area.
What does this complete program print? const observer=new window.IntersectionObserver(()=>{},{threshold:[1,0.5,0]});console.log(JSON.stringify(observer.thresholds));observer.disconnect();
- [1,0.5,0]
- [0.5]
- [0,0.5,1]
- [0,1]
Answer: [0,0.5,1]. The threshold list is sorted.
What can cause the first callback after observe(target)?
- Only a user scroll
- Only a network response
- Only a resize
- The initial observation itself
Answer: The initial observation itself. Registration schedules an initial observation even without user scrolling.
What does this complete program print? const observer=new window.IntersectionObserver(()=>{},{rootMargin:"5px 10px"});console.log(observer.rootMargin);observer.disconnect();
- 5px 10px 5px 10px
- 5px 10px
- 5px
- 10px 5px 10px 5px
Answer: 5px 10px 5px 10px. The margin is exposed in its normalized four-sided form.
What does ordinary isIntersecting alone prove?
- The user read the content
- A geometric intersection condition
- The element is unobscured and opaque
- An ad impression meets every policy
Answer: A geometric intersection condition. Ordinary geometry observation does not establish attention or visual occlusion.
What does this complete program print? const observer=new window.IntersectionObserver(()=>{});console.log(observer.takeRecords().length);observer.disconnect();
- 1
- undefined
- 0
- TypeError
Answer: 0. With no observed targets or queued entries, there are no records to drain.
Which cleanup matches a terminal component disposal?
- Keep observing until the page closes
- Only clear the seen array
- Call observe again for each target
- Disconnect and prevent later callbacks from updating state
Answer: Disconnect and prevent later callbacks from updating state. The observer resource and component lifetime state need consistent cleanup.
Continue this course
- Previous: Web Workers (Background Threads)
- Next: MutationObserver (Watching the DOM) — Observe DOM changes — added nodes, attributes, and text
- Quick reference: JavaScript cheat sheet