Switch between divs while scrolling, using jQuery

Switch between divs while scrolling, using jQuery
0

#1

I am trying to make a portfolio page. Technologies I am using are HTML, CSS and jQuery. However, I am stuck at a problem involving scrolling my page up and down. U see, while I scroll down, I want to add a class on the navbar link, corresponding to the div I am on the page. While it happens, to some extent, while scrolling down, it just messes up while scrolling up.

Following is my code …
https://codepen.io/iamrkcheers/pen/KmxEpw

Any help is appreciated. Thank You.


#2

The easiest way, since you’re using jQuery, is to use ScrollSpy. This will highlight the nav button for your sections as you scroll through them. It does this by assigning the class active to your currently active nav link. ScrollSpy also fires an event every time it changes, so you can listen for that event and check which link is active. Here’s the rundown in code:

$('body').scrollspy(options).on('activate.bs.scrollspy', function(event) {
  var loc = $('li.active a').attr('href')
  // ... do stuff
})

So, if loc === "#home", or whatever, you can change your navbar’s class.