Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Scrollspy not working: Scrollspy is not a function

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

like image 331
Kait Jardine Avatar asked Dec 10 '22 04:12

Kait Jardine


1 Answers

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 });
like image 114
Nipun Ravisara Avatar answered Dec 28 '22 10:12

Nipun Ravisara