- Docs
Scroll Spy
What @samline/scroll-spy does, when a section is active, and how links, clicks and scroll containers fit together.
@samline/scroll-spy highlights the navigation link of the section being read. Put data-scroll-spy on a navigation of plain #id links and call autoScrollSpy() (or load the CDN script).
<nav data-scroll-spy aria-label="On this page">
<a href="#install">Install</a>
<a href="#usage">Usage</a>
</nav>
When a section is active
- An activation line sits 25% down the viewport (or the scroll container). Change it with
offset. - The active section is the last one whose top has crossed the line. Before the first section, nothing is active.
- At the very bottom of the page, the last section in view is active, so a short final section can still be reached.
- A clicked link becomes active at once and stays active until scrolling settles, so smooth scrolling never flickers through the sections in between.
The active link gets aria-current="true" and, if you set one, activeClass. Every link pointing to the same section is marked.
Pieces
| Job | How |
|---|---|
| Watch a navigation | data-scroll-spy, or scrollSpy(nav, options) |
| Move the line | offset / data-scroll-spy-offset: pixels or a percentage |
| Style the active link | [aria-current] in CSS, or activeClass |
| Sections in a panel | root |
| Long navigations | followActive (on by default) |
| Shareable URL | updateHash |
| React to changes | onChange({ id, section, links, previous }) |
Choose your next step
Package managers, the CDN and the first navigation.
ExamplesLive previews with the complete, copyable source of each one.
API referenceSignatures and behavior of scrollSpy, autoScrollSpy and window.ScrollSpy.
Attributes and options.
Layouts and containersSticky headers, scroll containers, smooth scrolling and nested lists.
Accessibility and navigationFocus, reduced motion and what your page provides.
Framework integrationsReact, Vue, Svelte, Astro and page swaps.