I encountered the following issue:
While trying to add logic to apply the active class on list elements in my navigation bar as I scroll, I utilized this code snippet:
$(window).bind('scroll', function () {
var scrollPos = $(window).scrollTop() + 100;
$('#nav-menu a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
currLink = currLink.parent();
if (refElement.position().top <= scrollPos) {
$('.nav > li').removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
});
Everything works correctly while scrolling and even when clicking on a link within the navigation bar. However, a problem arises when I have 5 links that correspond to different div sections. For example, if I am at the top of the page and click on the last link, the intermediate links also get the active class as I scroll through the content.
Is there a workaround to avoid assigning the active class to the links in between?
EDIT: Here is the code for click-to-scroll functionality:
// Page scroll
$('a.page-scroll').click(function () {
$(".nav > li").removeClass("active");
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 40
}, 900);
return false;
}
}
});