Guide

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

  1. An activation line sits 25% down the viewport (or the scroll container). Change it with offset.
  2. The active section is the last one whose top has crossed the line. Before the first section, nothing is active.
  3. At the very bottom of the page, the last section in view is active, so a short final section can still be reached.
  4. 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

JobHow
Watch a navigationdata-scroll-spy, or scrollSpy(nav, options)
Move the lineoffset / data-scroll-spy-offset: pixels or a percentage
Style the active link[aria-current] in CSS, or activeClass
Sections in a panelroot
Long navigationsfollowActive (on by default)
Shareable URLupdateHash
React to changesonChange({ id, section, links, previous })

Choose your next step