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.
<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.
<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>As you scroll the inner box, the matching nav-pill link automatically becomes activeScrollSpy watches scroll position inside the target element and highlights the nav-link whose section id is currently visible.
<body data-bs-spy="scroll" data-bs-target="#mainNav" data-bs-offset="70" tabindex="0">The whole page uses ScrollSpy, offsetting by 70px for a fixed navbardata-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.
