BS5 Scrollspy

Automatically update navigation based on scroll position using Bootstrap 5 Scrollspy for long pages and documentation layouts.

On this page

What is Scrollspy?

Scrollspy automatically updates active nav links based on the current scroll position. It is useful for documentation pages with sections.

Basic requirements

  • A scrollable container (or the body)
  • Target navigation with anchor links
  • Unique IDs for section headings

Example navigation

<nav id="docNav" class="nav flex-column">
  <a class="nav-link" href="#section1">Section 1</a>
  <a class="nav-link" href="#section2">Section 2</a>
  <a class="nav-link" href="#section3">Section 3</a>
</nav>

Example content with Scrollspy

<div data-bs-spy="scroll" data-bs-target="#docNav" data-bs-smooth-scroll="true"
     class="position-relative" tabindex="0" style="height: 300px; overflow: auto;">

  <h4 id="section1">Section 1</h4>
  <p>Content...</p>

  <h4 id="section2">Section 2</h4>
  <p>Content...</p>

  <h4 id="section3">Section 3</h4>
  <p>Content...</p>

</div>

Initialize via JavaScript (optional)

const el = document.querySelector('[data-bs-spy="scroll"]');
new bootstrap.ScrollSpy(el);

Common mistakes

  • Missing tabindex="0" on scroll container
  • Target nav links do not match section IDs
  • Container not scrollable (no fixed height or overflow)

Best practices

  • Use data-bs-smooth-scroll="true" for nicer UX
  • Keep section IDs short and predictable
  • Use Scrollspy for long pages only

BS5 Scrollspy Examples (8)