Scroll Spy Highlights Sections With IntersectionObserver
Highlight the section the reader is in with IntersectionObserver and a narrow rootMargin band, then sync aria-current on the matching nav link.
Code
// Scroll spy: a narrow rootMargin band in the middle of the viewport
// decides which section currently counts as "read"
const sections = [...document.querySelectorAll('main section[id]')];
const links = new Map<string, HTMLAnchorElement>();
const nav = document.querySelector('nav');
for (const section of sections) {
const link = document.createElement('a');
link.href = '#' + section.id;
link.textContent = section.querySelector('h2')?.textContent ?? section.id;
nav?.append(link);
links.set(section.id, link);
}
function setActive(id: string): void {
for (const [key, link] of links) {
link.classList.toggle('active', key === id);
link.setAttribute('aria-current', key === id ? 'true' : 'false');
}
}
const observer = new IntersectionObserver(
(entries) => {
const visible = entries
.filter((entry) => entry.isIntersecting)
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
if (visible.length > 0) setActive(visible[0].target.id);
},
// only the middle band of the viewport triggers highlighting
{ rootMargin: '-40% 0px -55% 0px' },
);
for (const section of sections) observer.observe(section);
setActive(sections[0]?.id ?? '');
console.log('scroll spy observing', sections.length, 'sections');How it works
Scroll Spy Highlights Sections With IntersectionObserver comes down to the function setActive.
Iteration is nested: for (const section of sections) frames the pass, for (const [key, link] of links) does the per-item step.
What to watch for
- This is browser-side code —
document,IntersectionObserverwill not resolve in Node.
Putting it to use
The primary signature is function setActive(id: string)
The demo output is labeled (scroll spy observing); each label names the call that printed it.
Core lines
link.textContent = section.querySelector('h2')?.textContent ?? section.id;
.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
setActive(sections[0]?.id ?? '');
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does Scroll Spy Highlights Sections With IntersectionObserver run in plain Node.js?
- No — it touches `document` and `IntersectionObserver`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.