![]() |
VOOZH | about |
Bootstrap 5 Scrollspy is used to automatically update the navigation links based on the scroll position, highlighting the corresponding section in the viewport.
To use scrollspy in Bootstrap 5, we need to add the data-bs-spy="scroll" attribute to the element that should be used for scrolling and specify the target by using the data attribute data-bs-target="".
How it works:
Syntax:
<tag data-bs-spy="scroll" data-bs-target="#..">
content...
</tag>
Bootstrap 5 Scrollspy Usage:
| Aspect | Description |
|---|---|
| Via data attributes | Initialize Bootstrap scrollspy using data attributes like data-bs-spy="scroll" and data-bs-target. |
| Via JavaScript | Initialize scrollspy via JavaScript by passing code inside a script tag. |
| Methods | Additional functionalities for scrollspy: refresh, dispose, getInstance, getOrCreateInstance. |
| Options | Pass scrollspy options through data attributes or JavaScript. Options include method, offset, and target. |
| Events | activate.bs.scrollspy event is automatically triggered when a new scrollspy element is activated. |
Example 1: In this example, Bootstrap 5 Scrollspy implementation with a sticky list-group for navigation. Utilizes `data-bs-spy="scroll"` and `data-bs-target="#list-example"` attributes for scroll tracking.
Output :
Example 2: In this example, Bootstrap 5 Scrollspy with a fixed-top navbar. Sections linked in the navbar navigate to corresponding content sections with smooth scrolling.
Output: