How to use the scrollspy component with list groups in Bootstrap

Scrollspy is a UI (user interface) design pattern. Scrollspy highlights the user's current location on a website by synchronizing the navigation menu or list group with the page's contents as the user scrolls through it.

Bootstrap provides the scrollspy component that automatically updates the navigation menu or list group component based on the user's scroll position. The scrollspy component is used to indicate the active link in the viewport. Scrollspy improves the user experience and makes navigation easier.

Scrollspy in Bootstrap

Follow the steps below to create a scrollspy on a list group in Bootstrap:

  1. First, we'll add the data-bs-spy attribute to the element we want to enable the scrollspy feature. Set the value of data-bs-spy attribute to scroll. This will activate the scrollspy feature.

  2. Add the data-bs-target attribute to the same element on which data-bs-spy was added in Step 1. Set the value of data-bs-target to the element's id that will be used as the list group (the navigational item). This tells the Bootstrap which element to synchronize with the scroll position.

  3. Create a list group using the .list-group class. Each list item in the menu should have an "href" attribute pointing to the page's corresponding section.

  4. Wrap each page section that corresponds to a link in the list group with a div with a unique ID. This lets the scrollspy know which page section is visible to the user.

Example

Free Resources