javascript
32 lines · 7 steps
Building a scroll spy with IntersectionObserver
Highlight the nav link for whichever section is currently in view, driven by the browser's IntersectionObserver.
Explained by
highlit
1function initScrollSpy() {
2 const links = Array.from(document.querySelectorAll('.nav a[href^="#"]'));
3 const sections = links
4 .map((link) => document.querySelector(link.getAttribute('href')))
5 .filter(Boolean);
6
7 const setActive = (id) => {
8 links.forEach((link) => {
9 link.classList.toggle('is-active', link.getAttribute('href') === `#${id}`);
10 });
11 };
12
13 const observer = new IntersectionObserver(
14 (entries) => {
15 const visible = entries
16 .filter((entry) => entry.isIntersecting)
17 .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
18
19 if (visible.length > 0) {
20 setActive(visible[0].target.id);
21 }
22 },
23 {
24 rootMargin: '-40% 0px -55% 0px',
25 threshold: [0, 0.25, 0.5, 0.75, 1],
26 }
27 );
28
29 sections.forEach((section) => observer.observe(section));
30
31 return () => observer.disconnect();
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1IntersectionObserver lets the browser report visibility changes instead of you polling scroll position on every frame.
- 2Sorting entries by intersectionRatio picks the most-visible section when several qualify at once.
- 3Returning a disconnect function gives callers a clean way to tear down the observer.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-scroll-spy-with-intersectionobserver-explained-javascript-033e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.