I want to change the width and left to the corresponding element, and when another button is clicked, switch the earlier button property back to –left: 50%; –width: 0;. So that only the button that was most recently clicked, has the 70% and 17.5% width and left. I am doing it this way, because I am changing :after properties.
const navButton = document.querySelectorAll('.nav-button');
const navListInside = document.querySelectorAll('.nav-list-inside');
for (let i = 0; i < navButton.length; i++) {
navButton[i].addEventListener('click', () => {
scroll(i);
navListInside[i].style.setProperty('--width', '70%');
navListInside[i].style.setProperty('--left', '17.5%');
});
}
#nav {
position: fixed;
width: 100%;
}
#list-nav {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 75px;
position: relative;
padding-top: 10px;
gap: 10px;
}
.nav-list-inside {
--left: 50%;
--width: 0;
display: flex;
justify-content: center;
align-items: center;
list-style: none;
font-size: 2rem;
/* padding: 0 10px; */
/* margin: 0 30px; */
position: relative;
width: 100%;
height: 100%;
}
.nav-list-inside:after {
content: "";
width: var(--width);
height: 3px;
background: var(--neon-blue);
position: absolute;
left: var(--left);
bottom: -10px;
transition: 0.5s;
}
.nav-button {
display: inline-block;
width: 100%;
height: 100%;
list-style: none;
font-size: 2rem;
padding: 0 10px;
margin: 0 20px;
position: relative;
color: white;
border: none;
background: none;
cursor: pointer;
}
<nav id="nav">
<ul id="list-nav">
<li class="nav-list-inside"><button class="nav-button">Name</button></li>
<li class="nav-list-inside"><button class="nav-button">Home</button></li>
<li class="nav-list-inside"><button class="nav-button">Services</button></li>
<li class="nav-list-inside"><button class="nav-button">About us</button></li>
<li class="nav-list-inside"><button class="nav-button">Contact us</button></li>
</ul>
</nav>
>Solution :
The main problem with your code is that you use the same variable i in all of your event listener functions, so i always has the same value. To avoid this, replace the for loop with a .forEach call.
Also, after setting the new properties for the clicked button, you must reset them for all other buttons.
navButton.forEach(function(button, i) {
button.addEventListener('click', () => {
scroll(i);
navListInside[i].style.setProperty('--width', '70%');
navListInside[i].style.setProperty('--left', '17.5%');
for (let j = 0; j < navButton.length; j++) if (j !== i) {
navListInside[j].style.setProperty('--width', '0');
navListInside[j].style.setProperty('--left', '50%');
});
});
Instead of manipulating the properties directly, you can also introduce a .pressed class as suggested in the other answer.