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.
Below is my HTML, CSS and Javascript(index.js)
<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>
li:hover:not(.active) {
background-color: rgb(91, 19, 114);
border-radius: 2vh;
}
.active {
background-color: rgb(132, 2, 175);
}
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');
});
});