Reputation:
I have two navs, both with the class of .fixed-nav
and would like to add a class to the active link of each nav (i.e. .menu__item--current
for the #main-nav
and .is-selected
for the #cd-vertical-nav
), based on scroll position (snippet below).
This part seems to be wrong:
updateMainNavigation(), updateVerticalNavigation();
$(window).on('scroll', function() {
updateMainNavigation(), updateVerticalNavigation();
});
My first try doesn't work:
updateMainNavigation();
$(window).on('scroll', function() {
updateMainNavigation();
});
updateVerticalNavigation()
$(window).on('scroll', function() {
updateVerticalNavigation();
});
Upvotes: 1
Views: 80
Reputation: 206
You can add a function to listen for scrolling. Calculate which div you are currently at and then select that element and change its css. You can tweak the number
calculation if you want it to change earlier. I would add a class to your vertical-navs
. In this case, class="vert-nav"
.
function changeDots(distanceFromTop) {
var number = Math.ceil(distanceFromTop / 400);
$('.cd-dot').css({background: "#fff"});
$('.is-selected').removeClass("is-selected");
if (distanceFromTop === 0) {
$($('.cd-dot')[0]).css({background: "#000"});
$($('.vert-nav')[0]).addClass("is-selected");
} else {
$($('.cd-dot')[number - 1]).css({background: "#000"})
$($('.vert-nav')[number - 1]).addClass("is-selected");
}
}
$(window).scroll(function() {
var distanceFromTop = $(this).scrollTop();
changeDots(distanceFromTop);
});
Here's an example: CodePen
Upvotes: 1