I have a navigation bar.
To start with only the first link (Homepage) has a class of 'active'.
I want to achieve the following:
when the user click on a different link the class of active is removed from wherever is present and is attributed to the link the user has clicked. So that only one link at a time is active.
const links = document.querySelectorAll('.navbar ul li a');
links.forEach((link) => {
link.addEventListener('click', () => {
link.classList.toggle('active');
});
});
.active {
background-color: #fc9d03;
}
<div class="navbar">
<ul>
<li><a href="#" class="active">Homepage</a></li>
<li> <a href="#">Blog Entries</a></li>
<li><a href="#">Food Gallery</a></li>
<li> <a href="#">Contact Us</a></li>
</ul>
</div>