Lesson 33 +10 XP

Scrollspy

Scrollspy

Scrollspy automatically updates the navigation links based on the scroll position, highlighting the section you are currently viewing. It is perfect for long pages with a nav menu.

How it works

  • Add data-bs-spy="scroll" to the scrolling element.
  • Set data-bs-target="#navmenu" to point at the nav list.
  • Add tabindex="0" to the scrollable element so it can receive focus.

Basic example

<body data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="50" tabindex="0">

  <nav id="navbar-example" class="navbar navbar-expand-sm bg-dark navbar-dark">
    <ul class="navbar-nav">
      <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>

  <div id="section1" class="container-fluid">Section 1 content</div>
  <div id="section2" class="container-fluid">Section 2 content</div>
  <div id="section3" class="container-fluid">Section 3 content</div>

</body>

The key pieces

  • Each nav link points to a section id (#section1 and so on).
  • Each section has a matching id.
  • data-bs-spy="scroll" activates scrollspy on the container.
  • data-bs-target names the nav list to update.
  • data-bs-offset controls the scroll offset in pixels.

TL;DR

  • Scrollspy highlights the nav link of the visible section.
  • Add data-bs-spy="scroll" and data-bs-target.
  • Nav links must match section ids.
  • Add tabindex="0" to the scrollable element.