Exploring vanilla js for the first time. I have a navigation bar with links to different sections on the webpage. My goal is to dynamically add an active class to the corresponding link as soon as its associated section becomes active. If there are no active sections, then the active class should be removed from all links. I came across a helpful script, but it has one drawback. When I scroll to an inactive section, the active class remains with the previous active section.
const links = document.querySelectorAll('.nav-link');
const sections = document.querySelectorAll('.forJS');
function changeLinkState() {
let index = sections.length;
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
links.forEach((link) => link.classList.remove('active'));
links[index].classList.add('active');
}
changeLinkState();
window.addEventListener('scroll', changeLinkState);
section{
height:100vh;
scroll-y:auto;
}
.nav-link.active{
color: red;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdafa2a2b9beb9bfacbd8df8e3fde3fde0afa8b9acff">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e1c11110a0d0a0c1f0e3e4b504e504e531c1b0a1f4c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<header class="fixed-top">
<nav class="navbar navbar-expand-lg navCustom">
<div class="container">
<ul class="navbar-nav justify-content-center">
<li class="nav-item">
<a class="nav-link" href="#main">Main</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#portfolio">Portfolio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contacts">Contacts</a>
</li>
</ul>
</div>
</nav>
</header>
<section class="forJS text-center">Some info 1</section>
<section class="forJS text-center">Some info 2</section>
<section class="forJS text-center">Some info 3</section>
<section class="text-center">Some info 4</section>
<section class="text-center">Some info 5</section>
<section class="text-center">Some info 6</section>
<section class="text-center">Some info 7</section>
<section class="text-center">Some info 8</section>
<section class="text-center">Some info 9</section>
<section class="forJS text-center">Some info 10</section>
</body>
P.S.Notes: Due to confusion in the script provided, "changeLinkState()" might need modification without parentheses and the empty condition within the "while" loop needs clarification.