In Bootstrap 5, the Scrollspy component is used to automatically update the navigation based on the user’s scroll position. It helps in highlighting the active section or item in the navigation menu as the user scrolls through the page. Here’s how you can use the Scrollspy component in Bootstrap 5:
- Set up the HTML structure with appropriate section IDs and a navigation menu:
<body data-bs-spy="scroll" data-bs-target="#navbar" data-bs-offset="50">
<nav id="navbar">
<ul class="nav">
<li class="nav-item"><a class="nav-link" href="#section1">Section 1</a></li>
<li class="nav-item"><a class="nav-link" href="#section2">Section 2</a></li>
<li class="nav-item"><a class="nav-link" href="#section3">Section 3</a></li>
</ul>
</nav>
<div id="section1">
<!-- Content of section 1 goes here -->
</div>
<div id="section2">
<!-- Content of section 2 goes here -->
</div>
<div id="section3">
<!-- Content of section 3 goes here -->
</div>
<!-- Initialize the scrollspy in JavaScript -->
<script>
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar',
offset: 50
})
</script>
</body>
In this example, the data-bs-spy="scroll"
attribute is added to the <body>
element to enable the Scrollspy behavior. The data-bs-target
attribute is set to the ID of the navigation menu (#navbar
), and the data-bs-offset
attribute defines the offset value from the top of the page for activating the navigation items.
The navigation menu is set up with a list of links, each pointing to a specific section of the page using the corresponding section ID (#section1
, #section2
, #section3
).
Inside the <body>
, the content of each section is placed within a <div>
element with the respective section ID.
To initialize the Scrollspy component, you need to include the JavaScript code shown above. This code creates a new instance of the ScrollSpy class and specifies the target element (document.body
) and the target navigation menu (#navbar
). The offset
option is set to 50 pixels to offset the activation of navigation items.
By default, Bootstrap will automatically handle the initialization of the Scrollspy component, so you don’t need to manually initialize it unless you have a specific requirement.
As the user scrolls through the page, the active section or item in the navigation menu will be highlighted based on their scroll position.
Feel free to use the Scrollspy component to create a dynamic navigation menu that reflects the user’s scroll position in your Bootstrap 5 project. For more details and additional options related to the Scrollspy component, refer to the official Bootstrap documentation.