Please help me implement bootstrap scrollspy!

Please help me implement bootstrap scrollspy!
0

#1

Here is a link to my codepen

I followed the bootstrap documentation for scrollspy

  1. Requires Bootstrap nav: I added the nav class to my <ul>element (see line 18 html)

  2. Requires relative positioning: I’ve applied position: relative to the body (see line 11 CSS)

  3. Via data attributes: I’ve added the data-spy=“scroll” and the data-target="#navbar-example" attributes to the body element (see line 9 HTML).

  4. Via Javascript: I’ve added $(‘body’).scrollspy({ target: ‘#navbar-example’ }) (see line 8 JS)

  5. My navbar links have resolvable id targets.

  6. I made sure that I loaded jQuery first and then boostrap.js

Even after all this, the scrollspy function does not seem to be working. I must be doing something wrong, but I have no idea what it could be. I’d appreciate any help from people who have successfully implemented scrollspy to their projects. Thanks!


#2

Hey. 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 link: 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 });

#3

Thank you so much! This resolved my issue!


#4

After I added https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js, the scrollspy feature started to work on my site. I took your advice and I also added data-offset=“50” to the body element. However, one thing I noticed is that when I click on the “portfolio” navbar link, the “about” navbar link seems to be the one that scrollspy marks as active. And when I click on the “about” navbar link, scrollspy doesn’t mark any navbar item as active. Any chance you would happen to know why this is happening? Thank you for your time!


#5

Actually, following your suggestion by adding $(‘body’).scrollspy({ target: ‘#navbar-example’, offset: 50 }); directly to the JS solved my issue. Please disregard my last question. Thanks again for all your help!


#6

In Codepen the HTML panel is your <body>. By adding another body tag you’re basically nesting another one in it. Add the offset via JS like I pointed out above and everything should work just fine.

You also don’t need an <head> tag, you can link all your scripts (fonts included) in the pen settings.

Glad you solved it!


#7

Thank you for the help! People like you make the FCC community awesome!