About Lesson
Introduction to Bootstrap 5 Scrollspy
- data-bs-spy=”scroll” → Enables Scrollspy on a container
- data-bs-target=”#navbarExample” → Links Scrollspy to a navigation element
- .nav & .nav-link → Defines navigation links
- .active → Highlights the active section
Example: Basic Scrollspy
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 5 Scrollspy</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
section {
height: 100vh;
padding: 50px;
}
</style>
</head>
<body data-bs-spy="scroll" data-bs-target="#navbarExample">
<!-- Navigation -->
<nav id="navbarExample" class="navbar navbar-light bg-light fixed-top">
<div class="container">
<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>
</div>
</nav>
<!-- Scrollable Content -->
<div class="container">
<section id="section1" class="bg-primary text-white">Section 1 Content</section>
<section id="section2" class="bg-success text-white">Section 2 Content</section>
<section id="section3" class="bg-danger text-white">Section 3 Content</section>
</div>
</body>
</html>
Output:

Explanation:
- The data-bs-spy=”scroll” enables Scrollspy on <body>.
- The data-bs-target=”#navbarExample” links Scrollspy to the navbar.
- As you scroll, the active section’s link in the navbar is highlighted automatically.