Menu

Bootstrap 5 Scrollspy


Previous


Next

Scrollspy

Scrollspy is used to automatically update links in a navigation list based on scroll position.

How To Create a Scrollspy

The following example shows how to create a scrollspy:

Example

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Bootstrap Example</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css” rel=”stylesheet”>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js”></script>
<style>
body {
position: relative;
}
</style>
</head>
<body data-bs-spy=”scroll” data-bs-target=”.navbar” data-bs-offset=”50″>

<nav>
<div>
<ul>
<li>
<a href=”#section1″>Section 1</a>
</li>
<li>
<a href=”#section2″>Section 2</a>
</li>
<li>
<a href=”#section3″>Section 3</a>
</li>
</ul>
</div>
</nav>

<div id=”section1″ style=”padding:100px 20px;”>
<h1>Section 1</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>

<div id=”section2″ style=”padding:100px 20px;”>
<h1>Section 2</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>

<div id=”section3″ style=”padding:100px 20px;”>
<h1>Section 3</h1>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
<p>Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>

</body>
</html>

Example Explained

Add data-bs-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element).

Then add the data-bs-target attribute with a value of the id or the class name of the navigation bar (.navbar). This is to make sure that the navbar is connected with the scrollable area.

Note that scrollable elements must match the ID of the links inside the navbar’s list items (<div id="section1"> matches <a href="#section1">).

The optional data-bs-offset attribute specifies the number of pixels to offset from top when calculating the position of scroll. This is useful when you feel that the links inside the navbar changes the active state too soon or too early when jumping to the scrollable elements. Default is 10 pixels.


Previous


Next

Scroll to Top