BBS5 Scrollspy

Learn how to create a scrollspy.

BS5 Scrollspy

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

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

Add data-bs-target with the ID of the navigation bar.

Examples

Scrollspy Example

html/css

Navigation updates as you scroll.

<!-- The scrollable area -->
<body data-bs-spy="scroll" data-bs-target=".navbar" data-bs-offset="50">

<!-- The navbar - The <a> elements are used to jump to a section in the scrollable area -->
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
...
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#section1">Section 1</a>
    </li>
    ...
</nav>

<!-- Section 1 -->
<div id="section1" class="container-fluid bg-success text-white" style="padding:100px 20px;">
  <h1>Section 1</h1>
  <p>Try to scroll this section and look at the navigation bar while scrolling!</p>
</div>
...

Test Your Knowledge

1. Which attribute initializes Scrollspy?

2. You need a matching ID on the link and the target section.