Bootstrap - Scrollspy Part 1: Introduction to Scrollspy
Scrollspy enables dynamic highlighting of navigation links as the user scrolls through sections of a webpage. It relies on Bootstrap's data attributes or JavaScript initialization.
Examples and Explanation
Basic Scrollspy Setup
<body data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="50">
<nav id="navbar-example" class="navbar navbar-light bg-light">
<a class="navbar-brand" href="#">Scrollspy</a>
<ul class="nav nav-pills">
<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>
</ul>
</nav>
<div id="section1" style="height: 600px;">Section 1 Content</div>
<div id="section2" style="height: 600px;">Section 2 Content</div>
</body>
Explanation: Adding data-bs-spy, data-bs-target, and data-bs-offset attributes to the body element initializes Scrollspy functionality.
Using data-bs-offset
<body data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="100">
Explanation: The data-bs-offset attribute adjusts the offset for activating navigation links based on the scroll position.
Highlight Active Links Bootstrap automatically applies the .active class to navigation links based on the current scroll position.