Bootstrap navbar with scrollspy
Bootstrap 5 gives you built-in scrollspy feature. When you scroll up or down it will add active
class to .menu-item
based on currently active viewport.
It does not mean that, if you click on certain menu the page will scroll. No, bootstrap's scrollspy just adds class according to your visible div or section. To make animated scroll effect on click (like landing page), we need to write our own script that forces page to scroll
This example also could be useful for landing page or any single page website
Steps to make scrollspy with smooth animation
- Create navbar on top of page
- Add few section on website and add unique ID for each of them
- Add same ID of each section to you link's href attribute
- Activate scrollspy function with data- attribute or via javascript
- Add
fixed-top
class on navbar or make it fixed at the top with any other method - With javascript:
var scrollSpy = new bootstrap.ScrollSpy(document.body, { target: '#navbarID' })
- With data- attribute to body tag:
data-bs-spy="scroll" data-offset="0" data-target="#navbar_ID"
Here are basic code snippets
Back to all examples