I am attempting to create a collapsing menu on click functionality with additional modifications. One of the changes I would like to implement is altering the background of another element when the menu collapses.
Currently, the code snippet only works for the first link, while the second toggleable link remains untargeted.
var pill = document.querySelector(".navpill");
var sub = document.querySelector(".submenu");
pill.onclick = () => {
sub.classList.toggle("collapse");
pill.classList.toggle("active");
}
.mainmenu {
background-color: #1f1f1f;
}
.navpill {
padding: 15px;
}
.navpill.active {
background: red;
}
.navpill a {
text-decoration: none;
color: white;
}
.submenu {
display: none;
}
.submenu.collapse {
display: block;
}
<div>
<ul class="mainmenu">
<li class="navpill"><a href="#">Link collapse 1</a>
<ul class="submenu">
<li class="navpill"><a href="#">sub Link 1</a></li>
<li class="navpill"><a href="#">sub Link 2</a></li>
<li class="navpill"><a href="#">sub Link 3</a></li>
<li class="navpill"><a href="#">sub Link 4</a></li>
</ul>
</li>
<li class="navpill"><a href="#">Link collapse 2</a>
<ul class="submenu">
<li class="navpill"><a href="#">sub Link 1</a></li>
<li class="navpill"><a href="#">sub Link 2</a></li>
<li class="navpill"><a href="#">sub Link 3</a></li>
</ul>
</li>
<li class="navpill"><a href="#">no link</a></li>
<li class="navpill"><a href="#">no link</a></li>
</ul>
</div>
An earlier solution I received helps the functionality work for all links, but I'm unsure how to introduce more variables and toggles to the function.
var pills = document.querySelectorAll(".expand");
pills.forEach(function(pill) {
pill.onclick = () => {
var sub = pill.querySelector(".submenu");
sub.classList.toggle("collapse");
}
});
I attempted adding this extra piece of code, but it was ineffective.
var navpill = pill.querySelector(".navpill");
navpill.classList.toggle("active");
If feasible, I would also appreciate a method to reset the actions taken when clicking on a different submenu.
Currently, using the aforementioned code does not close out the first link when the second is clicked, resulting in both remaining open simultaneously. My objective is to have only one link expand at a time.