In bootstrap, scrollspy is useful to highlight the navigation or list group items to indicate the currently active link based on the scroll position.
In bootstrap, the scrollspy will work with only nav components and list group items to show the active item based on the scroll. So, while creating the scrollspy you need to use either nav components or list group.
To create scrollspy in bootstrap, first create scrollable spying element (<body>
) with data-spy = "scroll"
, data-target = "#ScrollNavbar"
and optional data-offset = "0"
attributes by including the navigation bar and scrollable content elements like as shown below.
If you observe the above example, we added data-spy = "scroll"
attribute to the element (<body>
) to indicate the scrollable area, the data-target
attribute to connect nav component with id or class to scrollable area and the data-offset
attribute to specify the number of pixels to offset from top based on the position of scroll.
The bootstrap scrollspy requires relative positioning that’s why we added position: relative;
style property to the spying element (<body>
).
The scrollspy require scrollable elements ID must match with the links of nav component list items. If you observe the above example, the scrollable element <div id="sec1">
Id matches with the link of navbar <a href = "#sec1">
list item.
The above example will return the result like as shown below.
We can create vertical menu scrollspy by using navigation pills like as shown below.
The above example will return the result as shown below.
In bootstrap, we can create the scrollspy by using JavaScript with scrollspy()
method like as shown below.
This is how we can use the scrollspy to highlight the navigation or list group items to indicate the currently active link based on the scroll position.