scrollspy bootstrap 5

Scrollspy in Bootstrap 5 is a plugin that automatically updates the navigation based on the scroll position of the page. It adds an active class to the navigation link that corresponds to the section currently in view. This allows for easier navigation and provides visual feedback to the user about their current position on the page.

To use Scrollspy in Bootstrap 5, you need to follow these steps:

  1. Include the Bootstrap CSS and JavaScript files in your HTML document. You can either download them and host them locally or use a CDN. Here's an example using a CDN:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  1. Create a navigation menu with anchor links that correspond to the sections on your page. For example:
<nav id="navbar">
  <ul class="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>
  1. Add the data-bs-spy and data-bs-target attributes to the <body> tag. The data-bs-spy attribute specifies that Scrollspy should be enabled, and the data-bs-target attribute specifies the target element that contains the navigation links. For example:
<body data-bs-spy="scroll" data-bs-target="#navbar">
  <!-- Your page content here -->
</body>
  1. Add the scrollspy class to the target element that contains the sections you want to spy on. For example:
<div id="navbar" class="scrollspy">
  <section id="section1">
    <!-- Section 1 content -->
  </section>
  <section id="section2">
    <!-- Section 2 content -->
  </section>
  <section id="section3">
    <!-- Section 3 content -->
  </section>
</div>

Now, when you scroll the page, Bootstrap will update the navigation links and add the active class to the appropriate link based on the current scroll position. This provides a visual indicator to the user of their current position on the page.

Note that you may need to adjust the styling and positioning of the navigation links to fit your specific design. Additionally, you can customize the behavior of Scrollspy by using JavaScript and the available options provided by Bootstrap.