CKTIS / JavaScript
IntersectionObserver options: root, rootMargin, and threshold
Choose the reference area with `root`, adjust its bounds for the calculation with `rootMargin`, and use `threshold` to specify which fractions of the target’s area trigger notifications.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
new IntersectionObserver(callback, { root: null, rootMargin: "0px", threshold: [0, 0.5, 1] })The IntersectionObserver root/rootMargin/threshold options configure a browser Web API, not an ECMAScript feature. root chooses the reference area: omit it or pass null to use the top-level document’s viewport. An explicit root can be a Document or an Element, such as a scroll container. With an element root, the target must be its descendant in the layout’s containing-block chain.
rootMarginis a string of one to four CSS absolute lengths or percentages expanded like CSSmargin: top, right, bottom, left. The specification converts absolute lengths such ascmto pixels during parsing. For browser compatibility, usepxor%, since some implementations reject other absolute units. Each side defaults to0px. Percentages are relative to the width of the undilated root rectangle, even for top and bottom. Positive offsets expand the rectangle used for the calculation; negative offsets shrink it. This does not change layout or undo clipping by intervening ancestors. For cross-origin targets, the margin is ignored andentry.rootBoundsisnull.
thresholdaccepts one number or an array of numbers from0to1inclusive. Omission or an empty array gives a threshold of0. The constructor option isthreshold, singular; the read-onlyobserver.thresholdsproperty returns a numerically sorted array. An out-of-range threshold throws aRangeError; an invalidrootMarginthrows aDOMExceptionnamedSyntaxError.
After
observe(target), the callback asynchronously receives an initial entry even if the target does not intersect. Further entries are queued when a threshold is crossed in either direction orentry.isIntersectingchanges, not on every ratio change.0.5means half the target’s bounding-box area, not half the root’s area. Edge contact can giveisIntersecting: truewithintersectionRatio: 0. For a zero-area target box, the ratio is1ifisIntersectingis true and0otherwise. Geometric intersection does not prove the user can see the target.
The options are fixed at construction. To change them, create a new observer. Use
unobserve(target)to stop watching one target ordisconnect()to stop watching them all. Check support in the environment where the code will run.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IntersectionObserver options</title>
</head>
<body>
<script>
{
const root = document.createElement("div");
const spacer = document.createElement("div");
const target = document.createElement("div");
root.style.cssText = "width: 120px; height: 100px; overflow: hidden";
spacer.style.height = "120px";
target.style.cssText = "height: 40px; background: teal";
root.append(spacer, target);
document.body.append(root);
const observer = new IntersectionObserver(([entry], observer) => {
console.log(`root matches: ${observer.root === root}`);
console.log(`rootMargin: ${observer.rootMargin}`);
console.log(`thresholds: ${JSON.stringify(observer.thresholds)}`);
console.log(`isIntersecting: ${entry.isIntersecting}`);
console.log(`intersectionRatio: ${entry.intersectionRatio}`);
observer.disconnect();
root.remove();
}, {
root,
rootMargin: "0px 0px 40px",
threshold: [1, 0, 0.5],
});
observer.observe(target);
}
</script>
</body>
</html>Result
root matches: true rootMargin: 0px 0px 40px 0px thresholds: [0,0.5,1] isIntersecting: true intersectionRatio: 0.5
Save the example as an HTML file, open it in an active browser tab, and check the developer console for the output. The target starts 20 px below the root’s bottom edge. The 40 px bottom margin includes half the target’s height across its full width, so the initial entry reports `intersectionRatio: 0.5`. The code disconnects the observer and removes the demo elements.
Related lessons
- JavaScript · Lesson 30 · Intermediate · Version: 3
Sources
- IntersectionObserver: IntersectionObserver() constructor
- Intersection Observer API
- IntersectionObserver: rootMargin property
- Intersection Observer specification — Parse a margin
- IntersectionObserver: thresholds property
- IntersectionObserver: observe() method
- IntersectionObserverEntry: intersectionRatio property
- IntersectionObserverEntry: isIntersecting property
- IntersectionObserver: disconnect() method
- HTML Standard — Update the rendering