VOOZH about

URL: https://www.geeksforgeeks.org/bootstrap/bootstrap-5-scrollspy/

⇱ Bootstrap 5 Scrollspy - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bootstrap 5 Scrollspy

Last Updated : 23 Jul, 2025

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:

  • First, you need to add a data-bs-spy="scroll" attribute to the element that should be used for the scrollable area.
  • Next, you need to add a data-bs-target attribute to the navigation menu, which should contain the ID of the element that should be used as the scrollable area. 
  • Finally, you need to add a href attribute to each menu item that corresponds to the ID of a section on the page.

Syntax:

<tag data-bs-spy="scroll" data-bs-target="#..">
content...
</tag>

Bootstrap 5 Scrollspy Usage:

AspectDescription
Via data attributesInitialize Bootstrap scrollspy using data attributes like data-bs-spy="scroll" and data-bs-target.
Via JavaScriptInitialize scrollspy via JavaScript by passing code inside a script tag.
MethodsAdditional functionalities for scrollspy: refresh, dispose, getInstance, getOrCreateInstance.
OptionsPass scrollspy options through data attributes or JavaScript. Options include method, offset, and target.
Eventsactivate.bs.scrollspy event is automatically triggered when a new scrollspy element is activated.

Examples of Bootstrap Scrollspy

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:

Comment

Explore