Bootstrap ยท Chapter 29 of 43

Bootstrap ScrollSpy

ScrollSpy automatically highlights navigation links based on which section of the page is currently scrolled into view. It's great for single-page sites with a sticky navigation menu.

ScrollSpy is applied to the scrollable container (often the <body>) with data-bs-spy="scroll" and data-bs-target pointing at the nav element that should be updated.

Syntax
<body data-bs-spy="scroll" data-bs-target="#navbar">

Setting up ScrollSpy

Add data-bs-spy="scroll", data-bs-target="#navId", and a data-bs-offset value to the scrollable element. Each page section needs a matching id that corresponds to a nav link's href.

Requirements

The nav element being spied on must use Bootstrap nav or list-group markup, and each linked section must have a unique id for ScrollSpy to track correctly.

Example 1 (html)
<nav id="navbar" class="nav nav-pills">
  <a class="nav-link" href="#section1">Section 1</a>
  <a class="nav-link" href="#section2">Section 2</a>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbar" data-bs-offset="0" tabindex="0" style="height: 200px; overflow-y: scroll;">
  <h4 id="section1">Section 1</h4>
  <p>Content...</p>
  <h4 id="section2">Section 2</h4>
  <p>More content...</p>
</div>
Output
As you scroll the inner box, the matching nav-pill link automatically becomes active

ScrollSpy watches scroll position inside the target element and highlights the nav-link whose section id is currently visible.

Example 2 (html)
<body data-bs-spy="scroll" data-bs-target="#mainNav" data-bs-offset="70" tabindex="0">
Output
The whole page uses ScrollSpy, offsetting by 70px for a fixed navbar

data-bs-offset accounts for a fixed navbar's height so highlighting triggers at the right scroll position.

Key points

  • ScrollSpy highlights nav links based on scroll position.
  • data-bs-target points to the nav element to update.
  • Each section needs a unique id matching a nav link's href.
  • data-bs-offset adjusts for fixed headers so highlighting feels accurate.
๐Ÿ’ก Note: ScrollSpy requires the scrollable element to actually have scrollable overflow content, or it won't detect scroll position changes.

๐Ÿ“ Quick Quiz

1. What does ScrollSpy do?

2. What must each linked section have?

3. What does data-bs-offset help with?