I want to create a sidebar that when clicked, only changes 1, the rest are gone.
For example as below:
let button = document.querySelectorAll("aside li a");
for (let i = 0; i < button.length; i ) {
button[i].addEventListener("click", function() {
this.classList.toggle("is-active");
});
}
aside ul {
position: fixed;
list-style-type: none;
margin: 0;
padding: 0;
width: 190px;
left: 355px;
}
aside li a {
position: relative;
display: block;
padding: 5px 20px;
color: #145CA6;
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
font-size: 20px;
text-decoration: none;
top: 100px;
}
aside li a:hover,
aside li a.is-active {
color: #fff;
background-color: #145CA6;
transition: all 1s;
}
<aside>
<ul>
<li><a href="#tg">Overview</a></li>
<li><a href="#research-objective">Research</a></li>
<li><a href="#research">Interview</a></li>
<li><a href="#user-journey">User Journey</a></li>
<li><a href="#user-persona">Persona</a></li>
<li><a href="#ideation">Ideation</a></li>
<li><a href="#wireframe">Wireframe</a></li>
<li><a href="#final-design">Final Design</a></li>
<li><a href="#design-system">Design System</a></li>
</ul>
</aside>
Maybe there is another way besides creating a toogle and adding it in css? Because I'm confused about it.
Thanks :)
CodePudding user response:
One solution is remove all is-active
class from other buttons
before add for the clicked button
let buttons = document.querySelectorAll("aside li a");
for (let i = 0; i < buttons.length; i ) {
buttons[i].addEventListener("click", function() {
buttons.forEach(button => button.classList.remove('is-active'));
this.classList.add("is-active");
});
}
aside ul {
position: fixed;
list-style-type: none;
margin: 0;
padding: 0;
width: 190px;
left: 355px;
}
aside li a {
position: relative;
display: block;
padding: 5px 20px;
color: #145CA6;
font-family: 'Poppins';
font-style: normal;
font-weight: 400;
font-size: 20px;
text-decoration: none;
top: 100px;
}
aside li a:hover,
aside li a.is-active {
color: #fff;
background-color: #145CA6;
transition: all 1s;
}
<aside>
<ul>
<li><a href="#tg">Overview</a></li>
<li><a href="#research-objective">Research</a></li>
<li><a href="#research">Interview</a></li>
<li><a href="#user-journey">User Journey</a></li>
<li><a href="#user-persona">Persona</a></li>
<li><a href="#ideation">Ideation</a></li>
<li><a href="#wireframe">Wireframe</a></li>
<li><a href="#final-design">Final Design</a></li>
<li><a href="#design-system">Design System</a></li>
</ul>
</aside>