I am trying to add a class on the unordered list item when I click on it and a the same time it should be removing the same class from other list item.
I have tried using the below JavaScript logic but I am not getting the desired results. When I am including e.preventDefault()
then it is not redirecting me to the desired page but it is removing and adding the class to the list item. And when I am excluding e.preventDefault()
then it is redirecting me to the desired page but it is not removing and adding the class.
var links = document.querySelectorAll('li');
links.forEach(function(element) {
element.addEventListener('click', function(e) {
// PreventDefault to prevent redirect
e.preventDefault();
links.forEach(async function(element) {
// element.preventDefault()
await element.classList.remove('active');
});
this.classList.add('active');
});
});
li:hover:not(.active) {
background-color: rgb(91, 19, 114);
border-radius: 2vh;
}
.active {
background-color: rgb(132, 2, 175);
}
<div id="user-account-menu">
<ul class="side-nav">
<li class="">
<a href="/me">
Settings
<img class="navItems-icons" src="img/icons/settings.png" alt="settings">
</a>
</li>
<li class="active">
<a href="/create-user">
Create User
<img class="navItems-icons" src="img/icons/create-user.png" alt="create-user">
</a>
</li>
</ul>
</div>
2
Answers
Please remove async/await from internal forEach. Without async/await it will run synchronously before propagated default behaviour (redirecting) takes action.
I tried it that way, and it works, it removes ‘active’ class from other list item before redirecting (I can see it for a little moment before redirection occurs):
you could just add a control for not self remove the class
check if this can help you in some way: