Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Scroll Spy for Astro

Track scroll progress on a page or section with visual indicators. Choose from built in variants or add your own.

Scroll through the examples below. Each indicator stays in view while its section scrolls from start to finish. The next example then takes its place. You can also open the orbit indicator in a full-page preview.

Composition

ScrollSpy is a polymorphic HTML container. It renders a div by default, or the tag given with as. It does not use a custom element or a client framework. With no children, the root passes variant and orientation to its built-in track and indicator:

<ScrollSpy />
<ScrollSpy orientation="horizontal" />
<ScrollSpy variant="gooey" />
<ScrollSpy variant="orbit" />

The default vertical line sits at the right edge. The horizontal line sits at the top. Both track vertical scroll distance, from 0 at the top to 1 at the bottom. A page with no scroll range stays at 0.

The previews use scrollTarget="html" and a progressTarget section. A sticky wrapper keeps the indicator visible during that section. These previews disable viewport controls so the sticky wrapper follows the page scroll.

Line

Scroll through this section to fill the indicator.

0% at the start · 100% at the end

Installation

bunx --bun shadcn@latest add @gnostic/scroll-spy

Track and fill

Use parts when you need more control. Each part accepts class, style, native HTML attributes, and a slot. The root, track, and indicator also accept as.

---
import {
  ScrollSpy,
  ScrollSpyTrack,
} from "@/components/ui/scroll-spy"
---

<ScrollSpy orientation="horizontal">
  <ScrollSpyTrack orientation="horizontal" class="h-1" />
</ScrollSpy>

ScrollSpyTrack includes the growing line or SVG ring. Use fill={false} to omit it. Its slot accepts an indicator, section links, or custom content alongside the built-in fill. The TOC track includes its SVG markup directly; it does not need a separate TOC component file.

Custom slotted parts take variant and orientation as explicit props. These props choose classes and markup during Astro rendering. The root does not pass props into supplied slot content. Keep the visual props consistent with the root; in particular, a TOC needs variant="toc" on the root, track, and items.

Tracks default to line; indicators and items default to rail. All parts default to vertical orientation. A variant renders only the markup it uses.

The --scroll-spy CSS property is a number from 0 to 1. Custom content can use it to draw a different shape without another scroll script.

Indicators

ScrollSpyIndicator is optional. Its rail variant groups section items. The gooey variant supplies four liquid dots and a moving blob. The orbit variant supplies a dot that travels around the ring. A slot replaces its default content, so you can supply your own marks or SVG.

Gooey

The inactive dots use a gradient from muted to primary. A background layer keeps the dots visible through the blur filter.

Gooey

Scroll through this section to fill the indicator.

0% at the start · 100% at the end

Orbit

The track owns the ring; the indicator owns the orbiting dot. Use an orbit track without an indicator for a plain ring. This example uses scroll-spy:progress to update the percentage inside the ring. The number stays upright while the dot moves around it.

Orbit

Scroll through this section to fill the indicator.

0%

0% at the start · 100% at the end

Horizontal

Orientation changes the layout, not the scroll axis. A horizontal line or a row of dots can show progress through the same vertical page.

Horizontal

Scroll through this section to fill the indicator.

0% at the start · 100% at the end

Use as="nav" and give the navigation an accessible name. Items are native anchors. Use href="#section-id" to refer to a section; id remains the native ID of the link itself. This avoids duplicate IDs on the link and its target.

---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyIndicator,
  ScrollSpyItem,
} from "@/components/ui/scroll-spy"

const items = [
  { id: "about", label: "About" },
  { id: "work", label: "Work" },
]
---

<ScrollSpy variant="rail" as="nav" aria-label="Page sections">
  <ScrollSpyTrack variant="rail">
    <ScrollSpyIndicator variant="rail">
      {items.map(item => (
        <ScrollSpyItem href={`#${item.id}`}>
          {item.label}
        </ScrollSpyItem>
      ))}
    </ScrollSpyIndicator>
  </ScrollSpyTrack>
</ScrollSpy>

<section id="about">...</section>
<section id="work">...</section>

Keep items in document order. Content can be text, an icon, or both. A current, hovered, or focused item shows its content and expands its mark. To omit visible labels, leave the slot empty and supply an aria-label:

Start — scroll to the next section.

Middle — scroll to the next section.

Finish — scroll to the next section.

Empty items get a fallback accessible name from their fragment target. Supply a clear aria-label for an icon-only item. No item list, labels, or section IDs are needed when you only want total progress.

For a compact rail, set gap={8} on ScrollSpy. This sets an 8px distance between notch centers. A number uses pixels; a string accepts a CSS length, such as gap="0.5rem". It works in both orientations. Labels sit beside a vertical rail or above a horizontal rail, so they do not increase the spacing. Omit gap to keep the standard link target sizes. For a dense rail, also provide a section menu with larger touch targets.

Table of contents

variant="toc" draws a path beside the links. The line steps inward when the heading depth changes. All links whose targets intersect the scroll viewport get data-active. The highlight covers the path from the first active link to the last. There is no moving dot.

Link to heading IDs to track visible headings, or section IDs to track visible section content. Between headings, the last heading above the viewport stays active. Only the first active link gets aria-current="location". With progressTarget, the highlight clears when that target leaves the viewport.

Omit position to keep the list in normal flow. Add sticky when the list should remain on screen.

Set depth to the heading level. Depth 2 is a page section. Depth 3 and 4 step the path inward. The default is 2.

---
import {
  ScrollSpy,
  ScrollSpyTrack,
  ScrollSpyItem,
} from "@/components/ui/scroll-spy"

const items = [
  { id: "overview", label: "Overview", depth: 2 },
  { id: "flags", label: "Flags", depth: 3 },
]
---

<ScrollSpy variant="toc" as="nav" aria-label="On this page">
  <ScrollSpyTrack variant="toc">
    {items.map(item => (
      <ScrollSpyItem variant="toc" href={`#${item.id}`} depth={item.depth}>
        {item.label}
      </ScrollSpyItem>
    ))}
  </ScrollSpyTrack>
</ScrollSpy>

With the Toc component

Toc supplies a navigation wrapper, title, and list structure. Its TocMenuLink renders the active state supplied by its props. Scroll Spy supplies live heading tracking and the path highlight.

Compose Toc, TocTitle, TocMenu, and TocMenuItem with Scroll Spy. Use ScrollSpyItem variant="toc" for each link. Keep ScrollSpy as a div inside Toc, which already renders a nav.

<Toc aria-label="On this page">
  <TocTitle>On this page</TocTitle>
  <ScrollSpy variant="toc" scrollTarget="html">
    <ScrollSpyTrack variant="toc">
      <TocMenu>
        <TocMenuItem>
          <ScrollSpyItem variant="toc" href="#overview" depth={2}>
            Overview
          </ScrollSpyItem>
        </TocMenuItem>
      </TocMenu>
    </ScrollSpyTrack>
  </ScrollSpy>
</Toc>

The short sections below put several headings in view at once. The example uses the Toc wrapper and list parts. Scroll to see the highlight change as headings enter or leave the viewport.

Overview

Start with the features your site needs.

Install

Add the package to your project.

Flags

Set options for your build.

Addons

Add optional tools when you need them.

Deploy

Build the site for production.

Hosting

Publish the build to your host.

Next steps

Check the pages and links on your site.

scroll-spy-toc.ts is the internal path-drawing helper used by ScrollSpyTrack. Use the exported Astro parts for composition. The TOC link content comes from the slot in ScrollSpyItem, while href names the heading it tracks.

Position and scroll source

Position Effect
position="fixed" Keeps the indicator at the viewport edge.
position="absolute" Anchors the indicator inside a positioned ancestor.
position="relative" Keeps the indicator in normal flow.
Tailwind classes Set offsets, or change positioning to sticky.

The script finds the nearest ancestor with vertical overflow: auto, scroll, or hidden. If there is none, it uses document.scrollingElement. It uses the document’s <html> element if that property is null. A relative class controls the containing block for absolute positioning; it does not make that element scrollable. Use overflow-clip when you need clipping without a scroll source. Fixed positioning does not change which ancestor the script tracks.

To select a scroll container yourself, pass a CSS selector to scrollTarget:

<div id="reader" class="h-96 overflow-y-auto">
  <article class="min-h-288">...</article>
</div>

<ScrollSpy scrollTarget="#reader" />

The indicator can be outside the selected container. The selector uses the first matching HTML element in the document. Section links must point to sections inside that container. Use scrollTarget="html" or scrollTarget="body" to track the page explicitly.

The target must exist when the component initializes. An invalid selector or a missing target leaves the indicator empty. It does not track a different source. An omitted or blank selector keeps automatic parent detection.

Track one section

Use progressTarget to measure one section within the scroll container. The nearest matching ancestor is used first, then the first document match.

<section data-reading-section class="min-h-[160vh]">
  <div class="sticky top-24">
    <ScrollSpy
      scrollTarget="html"
      progressTarget="[data-reading-section]"
      position="relative"
    />
  </div>
</section>

For a nested scroll container, also set position: relative on that container so Motion can measure the section’s position.

Progress starts when the section top reaches the scroll viewport top. It ends when the section bottom reaches the viewport bottom. The section must be taller than the viewport; otherwise progress stays at 0. A missing or invalid target also stays at 0. Omit progressTarget to measure the whole scroll container.

With Scroll Area

Scroll Area works with the same component. Give its scrolling viewport an ID through viewportProps, then use that ID as the target:

Reading progress

Scroll inside the panel to fill the progress bar.

A quiet weekend

Choose a place

Pick somewhere close enough to reach without a long journey. A nearby town, a walking trail, or a small stretch of coast can give you space to slow down.

Pack less

Take comfortable shoes, a warm layer, and a book you want to read. Leave room in your bag for food from a local shop or something you find along the way.

Start on foot

Walk without a fixed route for the first hour. Look for a quiet street, a public garden, or a place to sit. Small details are easier to notice when you have time.

Make time for lunch

Choose a place where you can sit for a while. Try a local dish, ask about the area, or watch the street from a window. There is no need to rush to the next stop.

Leave an afternoon open

Keep part of the day free. You might find a museum, follow a path, or return to the same bench with your book. A good weekend does not need a full schedule.

Bring something back

Before you leave, write down one thing you want to remember. It can be a view, a conversation, or a new idea. Give yourself enough time for a calm journey home.

The viewport must have enough content to scroll. Target the inner viewport, not the outer ScrollArea wrapper. A ScrollSpy placed inside the viewport can omit scrollTarget and use automatic parent detection. Progress tracks the vertical scroll distance, including when the indicator uses a horizontal layout.

Behavior and access

animate from motion/mini animates the registered --scroll-spy property. Motion’s scroll() utility connects that animation to a native ScrollTimeline or ViewTimeline where supported, and uses JavaScript measurements otherwise.

scrollInfo() supplies the measurements for progress events, section links, and range checks, including when a native timeline controls the fill. For the rail, the component selects the active link at a reading line 45% down the viewport. The first and last links are selected at the scroll boundaries, including a short final section. Motion shares its scroll listener between instances that use the same container.

A view timeline uses the target’s nearest scroll container. When an explicit scrollTarget selects an outer container, or scroll padding would change the range, measured progress sets the mini animation’s time instead. The same fallback handles incomplete native timeline support. If animation creation fails, the script updates the local CSS property. Progress belongs to each component root; there is no document-wide Motion value.

Native timelines update with the scroll range. Motion refreshes section measurements when the viewport or scrollable content size changes. A section that becomes shorter than the viewport resets to 0 on either path. The script cancels Motion animations and listeners before Astro changes the page. It does not observe document mutations. For a new client-created root outside Astro navigation, call createScrollSpy(root) from scroll-spy.ts and retain the returned controller. Call controller.destroy() before removing or restarting that instance. The fill is decorative and does not announce every scroll update. Links retain native keyboard and fragment navigation.

JavaScript initializes the timelines and manages section links. With JavaScript off, native links still work and the fill stays empty.

All five variants share this scroll state. The TOC uses the same scroll listener to check which targets are visible. Its path drawing lives in scroll-spy-toc.ts. It does not need a separate visibility observer.

A reduced-motion preference removes mark transitions, the gooey filter, and the orbiting dot. The line and ring still show progress. The component does not set smooth scrolling.

API reference

See the installed source for the complete component files.

The root, track, and indicator default to div and accept an as prop. ScrollSpyItem is an anchor with a required href fragment, optional slot content, and native anchor attributes.

Browser controller and progress event

Import the browser API from @/components/ui/scroll-spy/scroll-spy.ts.

API Result
create(scope = document) Binds all unbound scroll-spy roots inside the scope and returns ScrollSpyController[].
createScrollSpy(root, options?) Binds one root and returns its ScrollSpyController. Repeated calls return the same controller.
controller.progress Current numeric progress from 0 to 1. Starts at 0 until the first measurement.
controller.destroy() Stops tracking, clears the binding, and resets progress and link state. Safe to call again.

ScrollSpyControllerOptions can override variant, scrollTarget, and progressTarget from the root’s data attributes. To change a bound instance, destroy it, then create it with the new options.

The root emits a bubbling scroll-spy:progress event after the first measurement and when progress changes. Its typed detail is { progress: number }. Progress is 0 when there is no scroll range, and 1 at the end of the range. Invalid or missing target selectors leave an inactive controller at 0. The controller emits no events after destruction.

Use the current value to set an initial total, then listen for changes:

import { createScrollSpy } from "@/components/ui/scroll-spy/scroll-spy.ts"

const root = document.querySelector<HTMLElement>("#reading-progress")!
const output = document.querySelector<HTMLOutputElement>("#reading-percent")!
const controller = createScrollSpy(root)

function updateTotal(progress: number) {
    output.value = `${Math.round(progress * 100)}%`
}

updateTotal(controller.progress)
root.addEventListener("scroll-spy:progress", (event) => {
    if (event.target === root) updateTotal(event.detail.progress)
})

Supply id="reading-progress" on ScrollSpy and use <output id="reading-percent">0%</output> for the total. Check event.target when listening on an ancestor or a root that contains another scroll spy.

The previous create(root) API returned a cleanup function. Replace it with createScrollSpy(root) and replace the cleanup call with controller.destroy().

ScrollSpyOptions

PropType
variant?NonNullable<ScrollSpyVariantProps['variant']>

The appearance passed to the built-in track and indicator. Set it explicitly on custom slotted parts. `toc` draws a path beside the links and highlights all visible targets.

TypeNonNullable<ScrollSpyVariantProps['variant']>
Defaultline
orientation?NonNullable<ScrollSpyVariantProps['orientation']>

The visual direction of the built-in parts. Both layouts track vertical scrolling.

TypeNonNullable<ScrollSpyVariantProps['orientation']>
Defaultvertical
position?NonNullable<ScrollSpyVariantProps['position']>

Fixed to the viewport, absolute in a positioned ancestor, or in normal flow. The `toc` variant uses normal flow when this is omitted.

TypeNonNullable<ScrollSpyVariantProps['position']>
Defaultfixed
gap?number | string

Distance between rail notch centers. Numbers are pixels; strings are CSS lengths. Omit for standard link targets.

Typenumber | string
scrollTarget?string

CSS selector for the scroll container. Defaults to the nearest scrollable ancestor, then document.scrollingElement.

Typestring
progressTarget?string

Track one section from its top to its bottom. The nearest matching ancestor is preferred.

Typestring

ScrollSpyTrackProps

PropType
variant?NonNullable<ScrollSpyVariantProps['variant']>

The visual style to render.

TypeNonNullable<ScrollSpyVariantProps['variant']>
Defaultline
orientation?NonNullable<ScrollSpyVariantProps['orientation']>

The visual direction.

TypeNonNullable<ScrollSpyVariantProps['orientation']>
Defaultvertical
fill?boolean

Render the line fill or orbit ring. Use false for custom content or an empty track.

Typeboolean
Defaulttrue

ScrollSpyIndicatorProps

PropType
variant?'rail' | 'gooey' | 'orbit'

The visual style to render.

Type'rail' | 'gooey' | 'orbit'
Defaultrail
orientation?NonNullable<ScrollSpyVariantProps['orientation']>

The visual direction.

TypeNonNullable<ScrollSpyVariantProps['orientation']>
Defaultvertical

ScrollSpyItemProps

PropType
variant?'rail' | 'toc'

A section rail link or a table-of-contents link.

Type'rail' | 'toc'
Defaultrail
orientation?NonNullable<ScrollSpyVariantProps['orientation']>

The direction of a rail item. TOC links stay in normal flow.

TypeNonNullable<ScrollSpyVariantProps['orientation']>
Defaultvertical
depth?number

Heading depth for the `toc` path. Depth 2 is a page section. Depth 3 and 4 step the line inward.

Typenumber
Default2

Theme and layout

Parts use the primary, foreground, background, and border tokens. Use Tailwind classes to set dimensions and offsets. Leave room beside content for fixed section links. Keep the rail short enough to fit on the smallest screen.

The parts contain their Tailwind classes. There is no separate ScrollSpy stylesheet. The root registers --scroll-spy as a number for the native progress animation. Each instance stores its progress value on its own root. The TOC uses --scroll-spy-track-top and --scroll-spy-track-bottom with local zero defaults. These values do not need property registration: the transition animates clip-path. Its slots are scroll-spy-toc, scroll-spy-toc-svg, scroll-spy-toc-path for the full path, and scroll-spy-toc-highlight for the visible range. The old spine and thumb slot names are removed.

The root uses CVA. Its scrollSpyVariants function and inferred ScrollSpyVariantProps type are exported from the component index.

Replace <ScrollSpyTrack><ScrollSpyFill /></ScrollSpyTrack> with <ScrollSpyTrack />. The separate fill component is removed. Set visual props on custom slotted parts explicitly. create() handles scroll progress and active links; it does not generate visual parts or change their classes.

The section rail takes its direction from Albina Nikiforova’s site. The contents spine takes its direction from the Fumadocs table of contents, as used on the Better-T-Stack docs.