I am currently working on a project where I want my navbar links to become active when clicked. My initial thought is to add the 'active' class when a link is clicked, but I'm unsure how to ensure that only one link is active at a time. Additionally, I am having trouble getting the code to run after the HTML has loaded, causing it not to work as expected.
let links = document.querySelectorAll('.nav-link');
links.addEventListener('click', function() {
this.classList.add('active');
});
I have tried using the above code to make the link active, but it doesn't seem to execute after the HTML has loaded, resulting in the desired effect not being achieved.
Link to JSFiddle for reference
TL;DR
- Struggling with removing active class from currently active link using JS
- Code for making clicked link active loads prior to HTML rendering, causing issues