Boost Navigation UX with Bootstrap JS Scrollspy
Want to automatically update your navigation links to highlight which section of the page is currently visible? Bootstrap’s Scrollspy component makes it easy!
It listens to page scroll events and adds an active class to your navigation links based on the scroll position, improving usability on long pages like documentation, portfolios, or landing pages.
Step 1: Include Bootstrap
Make sure you have Bootstrap CSS and JS loaded (Scrollspy depends on Bootstrap’s JavaScript):
Step 2: Setup HTML Structure
You need:
-
A nav menu with links referencing section IDs.
-
Content sections with matching IDs.
-
A container to spy on (usually
<body>or a scrollable div).
Example:
⚙️ Key Attributes Explained
-
data-bs-spy="scroll"activates Scrollspy on the container (here the whole<body>). -
data-bs-target="#navbar-example"tells Scrollspy which nav to update. -
data-bs-offset="100"offsets the scroll position for activating links (adjust based on header height). -
tabindex="0"is required for Scrollspy to work on<body>for keyboard accessibility.
Programmatic Initialization
You can also initialize Scrollspy with JavaScript:
Tips & Best Practices
-
Use smooth scrolling in CSS for nicer navigation:
-
Ensure sections have enough height to be scrollable.
-
Adjust
data-bs-offsetif you have fixed headers. -
Scrollspy works with any scrollable container, just target it correctly.
✅ Use Cases
-
Documentation pages with side nav
-
One-page landing sites with section nav
-
Long-form articles or portfolios
Final Thoughts
Bootstrap’s Scrollspy is a lightweight, easy way to enhance navigation and improve UX on content-heavy pages. Set up is straightforward, and it automatically handles active states on your nav links as users scroll.
