add image description hereI'm attempting to apply a class to the list item in an unordered list when clicked, while simultaneously removing the same class from the other list items.
I've tried using the JavaScript logic below, but I'm not achieving the desired outcome. When I include e.preventDefault()
, it prevents me from redirecting to the desired page, but successfully adds and removes the class from the list items. However, when I exclude e.preventDefault()
, it redirects me to the desired page but does not add or remove 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>