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:
First, we'll add the
data-bs-spyattribute to the element we want to enable the scrollspy feature. Set the value ofdata-bs-spyattribute toscroll. This will activate the scrollspy feature.Add the
data-bs-targetattribute to the same element on whichdata-bs-spywas added in Step 1. Set the value ofdata-bs-targetto the element'sidthat will be used as the list group (the navigational item). This tells the Bootstrap which element to synchronize with the scroll position.Create a list group using the
.list-groupclass. Each list item in the menu should have an "href" attribute pointing to the page's corresponding section.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.