Many page effects depend on whether something is visible: images that load only when you scroll to them, sections that fade in as they appear, and feeds that load more posts when you reach the bottom. The old way was to listen to every scroll event and measure element positions, which is slow and fiddly. The IntersectionObserver API does the measuring for you and calls your code only when an element enters or leaves view. This lesson builds two live examples: reveal-on-scroll and infinite scroll.
In this lesson you will learn
- Creating an observer and watching elements
- The entry object and
isIntersecting - The
root,thresholdandrootMarginoptions - Stopping with
unobserveanddisconnect - Building reveal animations and infinite scroll
You should know the DOM, events and async/await.
Reveal Elements as They Scroll into View
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>IntersectionObserver: reveal on scroll</title>
<style>
body { font-family: sans-serif; margin: 10px; font-size: 14px; }
#log { margin: 0 0 8px; padding: 6px 8px; background: #263238; color: #b2ff59; font-family: monospace; }
.scroller { height: 210px; overflow-y: auto; border: 2px solid #90a4ae; padding: 8px; }
.card {
margin: 16px 0; padding: 18px; border-radius: 8px; background: #e3f2fd;
opacity: 0; transform: translateY(20px); transition: opacity .5s, transform .5s;
}
.card.visible { opacity: 1; transform: none; }
.spacer { height: 120px; color: #90a4ae; }
</style>
</head>
<body>
<p id="log">Scroll the box below</p>
<div class="scroller" id="scroller">
<div class="spacer">Scroll down...</div>
<div class="card">Lesson 1: Variables</div>
<div class="card">Lesson 2: Functions</div>
<div class="card">Lesson 3: Closures</div>
<div class="card">Lesson 4: JSON</div>
<div class="card">Lesson 5: Timers</div>
<div class="spacer">End</div>
</div>
<script>
const log = document.getElementById("log");
const seen = new Set();
const observer = new IntersectionObserver(entries => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
entry.target.classList.add("visible"); // start the CSS transition
seen.add(entry.target.textContent);
observer.unobserve(entry.target); // each card only needs to appear once
}
log.textContent = `Revealed ${seen.size} of 5 cards`;
}, {
root: document.getElementById("scroller"), // watch visibility inside this box
threshold: 0.5, // fire when half the card is visible
});
document.querySelectorAll(".card").forEach(card => observer.observe(card));
</script>
</body>
</html>
Result
new IntersectionObserver(callback, options)creates an observer, andobserver.observe(element)starts watching an element. One observer can watch many elements.- The callback receives an array of entries, one for each element whose visibility changed.
entry.isIntersectingistruewhen the element is in view, andentry.targetis the element itself. - The callback adds the class
visible; CSS does the fade and slide with a transition. Keeping the animation in CSS keeps the JavaScript small. rootis the scrolling area to measure against. The default,null, means the browser window; here it is the scrolling box.threshold: 0.5fires when half the element is visible. Use 0 for “any part” or 1 for “fully visible”.- Each card only needs to appear once, so
unobserve(entry.target)stops watching it, saving work.
Infinite Scroll
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Infinite scroll</title>
<style>
body { font-family: sans-serif; margin: 10px; font-size: 14px; }
.feed { height: 230px; overflow-y: auto; border: 2px solid #90a4ae; }
.post { padding: 10px 12px; border-bottom: 1px solid #eceff1; }
#sentinel { padding: 12px; text-align: center; color: #607d8b; }
</style>
</head>
<body>
<div class="feed" id="feed">
<div id="list"></div>
<div id="sentinel">Loading...</div>
</div>
<script>
const list = document.getElementById("list");
const sentinel = document.getElementById("sentinel");
const PAGE = 8, TOTAL = 40;
let loaded = 0;
// Pretend server: returns a page of posts after a short delay
function fetchPage(from) {
return new Promise(resolve => setTimeout(() => {
const posts = [];
for (let i = from + 1; i <= Math.min(from + PAGE, TOTAL); i++) posts.push(`Post #${i}`);
resolve(posts);
}, 300));
}
let busy = false;
const observer = new IntersectionObserver(async ([entry]) => {
if (!entry.isIntersecting || busy) return;
busy = true;
const posts = await fetchPage(loaded);
for (const text of posts) {
const div = document.createElement("div");
div.className = "post";
div.textContent = text;
list.append(div);
}
loaded += posts.length;
busy = false;
if (loaded >= TOTAL) {
sentinel.textContent = `All ${TOTAL} posts loaded`;
observer.disconnect(); // stop watching: nothing left
}
}, { root: document.getElementById("feed"), rootMargin: "0px 0px 100px 0px" });
observer.observe(sentinel); // when the bottom marker comes near, load more
</script>
</body>
</html>
Result
- Instead of watching every post, the page watches a single sentinel element at the bottom of the list. When it comes into view, it is time to load more.
rootMargin: "0px 0px 100px 0px"grows the bottom edge of the root by 100px, so loading starts a little before the user reaches the end and the feed feels seamless.- The
busyflag prevents a second request starting while one is still loading. - New posts are added with
createElementandtextContent, which is safe even if the text comes from users. - After the last page,
disconnect()stops the observer completely and the sentinel shows a final message. fetchPagepretends to be a server with a 300ms delay. In a real site, replace it with a fetch call to your API.
Observer Options and Methods
| Name | Meaning |
|---|---|
root | The scrolling element to measure against; null means the window |
rootMargin | Grow or shrink the root’s edges, like CSS margin ("200px", "0px 0px -10% 0px") |
threshold | How much must be visible: a number from 0 to 1, or an array of them |
observe(el) / unobserve(el) | Start or stop watching one element |
disconnect() | Stop watching everything |
entry.intersectionRatio | How much of the element is visible, from 0 to 1 |
Common Mistakes
- Forgetting that the callback runs once at the start for every observed element, including those that are not visible. Always check
isIntersecting. - Loading the same page twice when the sentinel stays visible. Guard with a flag, as
busydoes. - Hiding content that search engines and screen readers need until JavaScript runs. Reveal animations should only change appearance.
- Using it for simple image lazy loading, where
<img loading="lazy">already does the job with no script.
Practice Exercises
Exercise 1. Log a message the first time an element with id footer becomes fully visible in the window.
Show answer
const io = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
console.log("Footer seen");
io.disconnect();
}
}, { threshold: 1 });
io.observe(document.getElementById("footer"));
Exercise 2. Pause a video when it scrolls out of view and play it when it comes back.
Show answer
const video = document.querySelector("video");
new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) video.play();
else video.pause();
}, { threshold: 0.5 }).observe(video);
Browsers only allow autoplay of muted videos, so add the muted attribute.
Frequently Asked Questions
Is IntersectionObserver better than a scroll event listener?
For visibility checks, yes. The browser calculates intersections efficiently and only calls your code when something changes, while a scroll listener runs many times per second and forces layout measurements.
Can it tell me which section is currently on screen?
Yes. Observe each section with a rootMargin such as "-50% 0px -50% 0px", which shrinks the root to a line across the middle of the screen. The section crossing that line is the current one, which is how many “table of contents” highlights work.
Summary
IntersectionObservercalls you back when elements enter or leave view.- Check
entry.isIntersectingand useentry.target. thresholdsets how much must show;rootMarginstarts work early.- Use
unobserveanddisconnectto stop when done.
