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 generateCalendarGrid(year, month) { const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0); const daysInMonth = lastDay.getDate();
Building a text calendar in JavaScript
date-handling
grid-layout
modular-arithmetic
Intermediate
9 steps
php
<?php final class MarkdownParser {
Building a small Markdown-to-HTML parser in PHP
state-machine
parsing
closures
Intermediate
10 steps
python
from typing import Callable, Dict, Type class PluginRegistry:
A decorator-based plugin registry in Python
decorators
registry pattern
factory
Intermediate
9 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 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.