Bootstrap Scrollspy not working: Scrollspy is not a function
Asked Answered
P

2

5

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

Peshitta answered 10/1, 2019 at 23:38 Comment(5)
You should be loading jquery twice, please check it, or upload full codeBaize
How do I load it twice? Just put the CDN in the HTML twice?Peshitta
I added the full codePeshitta
You don't need to add jQuery twice. You are missing the bootstrap.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.Lodie
I added bootsrap.js, however scrollspy still isn't working. It just lights up the Contact Me portion regardless of what section you're in. Also, I have content that I removed from the codepen for privacy reasons.Peshitta
F
10

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 });
Frequentative answered 11/1, 2019 at 2:32 Comment(0)
N
6

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

Nahshunn answered 17/12, 2020 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.