htmlcssbootstrap-5scrollspy

Bootstrap scollspy not functioning


I'm running into an issue with scrollspy on Bootstrap v5.1. I am following along with the examples within the docs (listed below) however I can't get it to work; nothing seems to change upon scrolling.

When the user scrolls on the page, depending on which section they are viewing I want the corresponding link on the navbar to be active.

HTML Outline

<body data-bs-spy="scroll" data-bs-target="#navbar">
    ...
    <nav id="navbar" class="menu">
    <ul class="nav flex-column">
        <li class="nav-item active"><a class="nav-link" href="#about">About me</a></li>
        <li class="nav-item"><a class="nav-link" href="#skills">Skills</a></li>
        <li class="nav-item"><a class="nav-link" href="#services">Services</a></li>
        <li class="nav-item"><a class="nav-link" href="#projects">Projects</a></li>                
    </ul>
    </nav>
    ...
    <section id="about"> ... </section>
    <section id="skills"> ... </section>
    <section id="services"> ... </section>
    <section id="projects"> ... </section>

</body>

Solution

  • It looks like your code is actually working, its just that the .active class is added to the .nav-link anchor tag instead of the .nav-item list item.

    Your CSS is targeting the li.active instead of a.active

    .sidebar .nav li a:hover, .sidebar .nav li.active a {
        color: #1d93e4;
        opacity: unset;
    }
    

    try this instead:

    .sidebar .nav li a:hover, .sidebar .nav li a.active  {
        color: #1d93e4;
        opacity: unset;
    }
    

    Here is the example of how to structure the nav (with the .active class in the .nav-link)

    <ul class="nav">
      <li class="nav-item">
        <a class="nav-link active" aria-current="page" href="#">Active</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled">Disabled</a>
      </li>
    </ul>
    

    https://getbootstrap.com/docs/5.1/components/navs-tabs/#base-nav

    Or like this...

    <nav class="nav">
      <a class="nav-link active" aria-current="page" href="#">Active</a>
      <a class="nav-link" href="#">Link</a>
      <a class="nav-link" href="#">Link</a>
      <a class="nav-link disabled">Disabled</a>
    </nav>