My one-page website has a fixed navbar that I want to change its active status when scrolling down to specific div positions.
Even though I tried using jQuery
, the code doesn't seem to work as intended. Here is the snippet:
// SMOOTH SCROLLING PAGES
$(document).ready(function () {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 800, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('main-navigation a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('main-navigation ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
};
Below is the HTML structure:
<nav id="main-navigation">
<ul>
<li class="active"><a href="#site-main">Home</a></li>
<li><a href="#a">A</a></li>
<li><a href="#b">B</a></li>
<li><a href="#c">C</a></li>
<li><a href="#d">D</a></li>
</ul>
</nav>
<div id="a">DIV Alpha</div>
<div id="b">DIV Bravo</div>
<div id="c">DIV Charlie</div>
<div id="d">DIV Delta</div>
Despite smooth scrolling working great, the issue arises when scrolling back up from div #d
- the active state of the navbar li doesn't update accordingly.