Skip to content
Calm motion: animations on this site only fade, with no movement

Scroll spy ​

useScrollSpy() shows which section is in view. It uses an IntersectionObserver over ids or a selector.

Basic
News — scroll the page; the nav follows.
Story — scroll the page; the nav follows.
Cast — scroll the page; the nav follows.
ts
const { active } = useScrollSpy(ids | selector, { rootMargin?, root? });
// ids: string[]           — element ids to observe
// selector: string        — or every element matching it
//                           either one can be a ref or a getter, which it follows
// rootMargin: string      — default "0px 0px -60% 0px"
// root: Ref<HTMLElement>  — a scroll container instead of the viewport
// active: Ref<string | undefined>

active is the id of the intersecting section whose top edge is nearest the top of the viewport. If you pass a scroll container, active uses the top of root instead. The composable measures this on every change. A long section that just scrolled past does not outrank the section that arrives. With the default rootMargin, only the top 40% of the viewport counts. A section becomes active at the upper part of the screen, not at the bottom edge. When nothing intersects (above the first section, or in a gap), active keeps its last value. Before any scroll, it is the first observed id.

Pair it with BlessSidebarNav :active as above. Give sections a scroll-margin-top equal to whatever sticks at the top, so a click does not land under the bar. The composable creates the observer on mount, so it is safe to call in server-rendered components. Sections can render later, for example behind a v-if or after a fetch. If so, pass the ids or the selector as a ref or a getter, such as () => sections.value.map((s) => s.id). When the value changes, the composable observes the new sections after they render.

Released under the MIT License. Character names and artwork belong to their owners.