When designing my website, I encountered an issue with the active navigation link style. It successfully changes when clicked and scrolled to the section, but does not update when the user scrolls away. How can I make the active style update on user scroll?
HTML code
<nav id="topNav" class="navbar navbar-expand-lg navbar-light ">
<a class="navbar-brand" href="#landing"><img id="brandLogo" src="project-images/portfolio logo2.png" alt=""></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#about">About <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#skills">Skills</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#projects">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</nav>
CSS code
.navbar {
position: fixed;
width: 100%;
height: 90px;
z-index: 1000;
margin: 0;
padding: 1.5rem 8rem !important;
/* background: #262626; */
background: transparent;
transition: 0.5s ease-out;
/* background: transparent !important; */
}
.navbar .navbar-nav a{
background: -webkit-linear-gradient(#e6e6ff, #6666ff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 20px !important;
margin: 10px;
padding: 10px 30px;
font-family: 'Ubuntu', sans-serif;
transition: 0.7s;
}
.navbar .navbar-nav a:hover {
background: -webkit-linear-gradient(#e6e6ff, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
/* color: #1b2735 !important;
border-radius: 30px; */
}
.nav-item{
background: transparent !important;
}
#topNav.scroll-menu {
background: #090a0f;
border-bottom: 0.5px solid #b3b3ff;
height: 90px;
box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2);
}
#topNav.scroll-menu a {
color: #0f1f3d !important;
transition: 0.6s ease-in-out;
}
#topNav.scroll-menu ul li.active a{
border: 1px solid #6666ff;
border-bottom: #6666ff;
border-radius: 30px;
}
#topNav.scroll-menu a:hover{
color: #fff;
}
JavaScript code
window.addEventListener("scroll", function(){
let topNav = document.getElementById("topNav");
if(window.pageYOffset > 750) {
topNav.classList.add("scroll-menu");
} else {
topNav.classList.remove("scroll-menu")
}
});
$(window).scroll(function(){
let position = $(this).scrollTop();
$('.section').each(function(){
let target = $(this).offset().top;
let id = $(this).attr('id');
if(position >= target) {
$('#topNav > ul > li > a').removeClass('active');
$('#topNav > ul > li > a [href=#' + id + ']').addClass('active')
}
})
});