โœฆ StealThis .dev

Anchor Navigation

Sticky in-page navigation that highlights the active section as you scroll, with smooth scroll-to-section on click.

Open in Lab
vanilla-js css
Targets: JS HTML

Code

Anchor Navigation

A sticky in-page sidebar navigation that uses IntersectionObserver to highlight the active section as you scroll. Clicking a link smooth-scrolls to the target section. No dependencies.

Features

  • Sticky sidebar that tracks scroll position
  • Active link highlighted with accent color and an animated left border indicator
  • Smooth scroll on click via scrollIntoView({ behavior: 'smooth' })
  • Reading progress bar at the top of the page
  • IntersectionObserver watches all section headings โ€” the topmost visible section wins

How it works

  1. Each section has a unique id. The sidebar links point to these IDs with href="#id"
  2. An IntersectionObserver with a negative top rootMargin fires when a section enters the viewport
  3. The observer tracks which sections are currently intersecting and highlights the one closest to the top
  4. Click handler calls e.preventDefault() then section.scrollIntoView() to animate smoothly without a hash jump

Accessibility

  • Nav uses <nav aria-label="On this page">
  • Active link receives aria-current="true"
  • Each section has a proper heading hierarchy starting with <h2>