4

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

Kait Jardine
  • 93
  • 1
  • 2
  • 13
  • You should be loading jquery twice, please check it, or upload full code – Levon Grigoryan Jan 10 '19 at 23:41
  • How do I load it twice? Just put the CDN in the HTML twice? – Kait Jardine Jan 11 '19 at 00:12
  • I added the full code – Kait Jardine Jan 11 '19 at 00:27
  • 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. – StaticBeagle Jan 11 '19 at 00:45
  • 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. – Kait Jardine Jan 11 '19 at 00:56

2 Answers2

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 });
Nipun Ravisara
  • 3,629
  • 3
  • 20
  • 35
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

Trí Phan
  • 1,123
  • 2
  • 15
  • 33
Ruben
  • 61
  • 1
  • 1