Bootstrap 4 scrollspy not working to change active navbar items

Just add this Jquery code

$(window).scroll(function(){
    $(".nav-item").removeClass("active");
    $(".active").parent().addClass("active");
  })

it will automatically add and remove active class to nav-item with reference to active nav-link


The ScrollSpy component is applying the active class to the nav-item, but you can't see it because you don't have navbar-light class in the navbar.

The Bootstrap 4 CSS selector that applies the style (darker text color) is this:

.navbar-light .navbar-nav .nav-link.active {
  color: rgba(0, 0, 0, 0.9);
}

So, just add the navbar-light class like this:

<nav id="main-nav" class="navbar navbar-expand-lg navbar-light bg-light bg-transparent fixed-top">
</nav>

Demo: https://www.codeply.com/go/ic6Md3e4y1


I spent a few days trying to solve this problem! I even set up a separate local website and copied code from W3Schools to build a clean page and couldn't get it to work. I finally tripped across this:

According to bootstrap documentation (https://getbootstrap.com/docs/4.3/components/scrollspy/), "When spying on elements other than the , be sure to have a height set and overflow-y: scroll; applied."

I added this: style="overflow-y: scroll; height: 1500px;" to the same element that has data-spy="scroll" data-target="#myScrollspy" and it started working. The magic one is the overflow-y: scroll. Not setting a height puts a horizontal scrollbar in an ugly place. Having a height of less than your screen height also puts a horizontal scrollbar on it. height: 100% didn't work, either.

Working example is here: http://www.ladybugsrule.net/BootstrapExamples/ScrollSpy.html