Skip to main content
VelinStyle v0.8.0
⌂ Home
  1. Docs
  2. Components
  3. Scrollspy

Scrollspy

The <velin-scrollspy> web component uses IntersectionObserver to automatically highlight the active navigation link as sections scroll into view.

Basic usage

Wrap a nav and scrollable content. The component matches href anchors to section IDs.

<velin-scrollspy>
  <nav slot="nav">
    <a href="#section-1">Section 1</a>
    <a href="#section-2">Section 2</a>
    <a href="#section-3">Section 3</a>
  </nav>

  <div slot="content">
    <section id="section-1">
      <h2>Section 1</h2>
      <p>Content for section one…</p>
    </section>
    <section id="section-2">
      <h2>Section 2</h2>
      <p>Content for section two…</p>
    </section>
    <section id="section-3">
      <h2>Section 3</h2>
      <p>Content for section three…</p>
    </section>
  </div>
</velin-scrollspy>

IntersectionObserver

Under the hood the component creates an IntersectionObserver with a configurable root-margin and threshold. When a section enters the viewport the corresponding nav link receives .active.

<velin-scrollspy root-margin="0px 0px -40% 0px" threshold="0">
  …
</velin-scrollspy>

The active link automatically receives .active. Style it however you like — it works with any nav pattern (list groups, tabs, vertical sidebars).

velin-scrollspy nav a.active {
  color: var(--velin-primary);
  font-weight: 600;
  border-inline-start: 3px solid var(--velin-primary);
}

Theme wählen