Bootstrap

Bootstrap Scrollspy

✅ How Scrollspy Works

Scrollspy watches a scrollable container (like <body> or a <div>) and updates classes on nav items (.nav-link) based on which target section is in view.


Basic Scrollspy Setup (Bootstrap 5)

✅ 1. Include Bootstrap CSS & JS

html
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap JS (includes Scrollspy) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

✅ 2. HTML Structure

html
<body data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-smooth-scroll="true" tabindex="0">

<!-- Navbar -->
<nav id="navbar-example" class="navbar navbar-light bg-light px-3 fixed-top">
<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>
<li class="nav-item">
<a class="nav-link" href="#section3">Section 3</a>
</li>
</ul>
</nav>

<!-- Content Sections -->
<div class="container" style="margin-top: 80px;">
<h4 id="section1">Section 1</h4>
<p style="height:600px;">Content 1...</p>

<h4 id="section2">Section 2</h4>
<p style="height:600px;">Content 2...</p>

<h4 id="section3">Section 3</h4>
<p style="height:600px;">Content 3...</p>
</div>

</body>


Key Attributes

Attribute Purpose
data-bs-spy="scroll" Activates Scrollspy on the container
data-bs-target="#..." Selector for the nav element to update
data-bs-smooth-scroll Optional: enables smooth scrolling
tabindex="0" Needed if target is body to make it focusable

⚠️ Notes

  • The target nav element must contain anchor tags (<a href="#section">) that match id attributes of content.

  • Scrollspy requires scrollable containers—usually <body> or a custom <div>.

  • The container must be large enough to scroll (set height and overflow-y: auto for custom containers).

Leave a Reply

Your email address will not be published. Required fields are marked *