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:
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
Share Improve this question edited Jan 11, 2019 at 0:27 Kait Jardine asked Jan 10, 2019 at 23:38 Kait JardineKait Jardine 1031 gold badge2 silver badges13 bronze badges 5 |2 Answers
Reset to default 10If 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 });
I had the same problem migrating from bootstrap 4.5 to 5.0. the fix was to replace:
$('body').scrollspy({ target: '#navbar-example' })
with:
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar-example'
})
see bootstrap documentation: https://getbootstrap.com/docs/5.0/components/scrollspy/#methods
jQuery
twice. You are missing thebootstrap.js
include in your pen though. Also, you might not see the scroll spy in all it's glory until your sections have content in them. If the sections are very narrow/thin it might look like it skips sections. – StaticBeagle Commented Jan 11, 2019 at 0:45