Position:

ScrollSpy Component

A navigation component that tracks scroll position and highlights the currently visible section. Supports smooth scrolling, sticky positioning, custom scroll containers, offset handling, and active state callbacks for building interactive page or documentation navigation.

Installation

Install the required packages:

This installs `flowbite-svelte` (Svelte components) and `flowbite` as development dependencies.

Basic Usage

The simplest way to use ScrollSpy is to provide an array of navigation items:

Features

Custom Positioning

You can position the navigation on the top, left, or right:

Offset for Fixed Headers

If you have a fixed header, use the offset prop to adjust when sections are considered "active":

Custom Active Styling

Customize the appearance of active navigation items:

Props Reference

PropTypeDefaultDescription
itemsScrollSpyItem[]requiredArray of navigation items
position'top'|'left'|'right''top'Position of the navigation bar
offsetnumber0Offset in pixels from top for active section calculation
stickybooleantrueEnable sticky positioning
activeClassstring''Custom Tailwind classes for active items
classstring''Custom Tailwind classes for the nav container
smoothScrollbooleantrueEnable smooth scroll behavior
onActiveChange(id: string) => voidundefinedCallback when active section changes
onNavigate(id: string) => voidundefinedCallback when navigation item is clicked

Accessibility

The ScrollSpy component is built with accessibility in mind:

  • Keyboard Navigation: Navigation items are fully keyboard accessible using Tab and Enter/Space
  • ARIA Support: Uses semantic HTML and aria-current for the active section
  • Visible Focus State: Focus rings are preserved for keyboard users
  • Screen Reader Friendly: Lists and links are announced correctly by assistive technology
  • Color Contrast: Default styles follow WCAG AA contrast guidelines

Best Practices

  • • Use clear, descriptive labels for each navigation item
  • • Ensure sufficient color contrast if overriding default styles
  • • Test with keyboard-only navigation and screen readers
  • • Provide meaningful and properly structured section headings