Bootstrap Scrollspy not working: Scrollspy is not a function

Kait Jardine picture Kait Jardine · Jan 11, 2019 · Viewed 7.2k times · Source

I'm making a one page website and I'm trying to get the navbar links to reflect what section of the page you're on. I've tried using it through HTML with no success. I had this code on the container that contains my different sections

<div class="container" data-spy="scroll" data-target="#navbar">

and the body is set to relative.

Since that wasn't working I tried using Scrollspy with javascript using this

$('.container').scrollspy({ target: '#navbar' })

Also with no luck. I have the jQuery CDN before the bootstrap CDN but I'm getting this error in the console. Uncaught TypeError: $(...).scrollspy is not a function

CodePen: https://codepen.io/kjardine/pen/VqEbaz

Answer

nipunravisara picture nipunravisara · Jan 11, 2019

If you check your console, you’ll see an error. Bootstrap 4 (at the moment) requires an additional js script to run properly. Add popper.js before Bootstrap 4 js file and the Scrollspy should work just fine. Here’s the cdn: https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js.

I also suggest to add a little bit of offset to compensate for the navbar’s height. This way the links will light up at the right time while scrolling or clicking. You can do it in your JS like so:

$('body').scrollspy({ target: '#navbar-example', offset: 50 });