I am trying to make a menu that collapses on click. I also want to add some more changes on that same function. For instance I want to change the background of another object.
In this snippet you can see it works on only the first link. The other toggleable link is not targeted.
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 1</a></li>
<li class="navpill"><a href="#">sub Link 1</a></li>
<li class="navpill"><a href="#">sub Link 1</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 1</a></li>
<li class="navpill"><a href="#">sub Link 1</a></li>
</ul>
</li>
<li class="navpill"><a href="#">no link</a></li>
<li class="navpill"><a href="#">no link</a></li>
</ul>
</div>
From a previous answer I got this piece of code which makes it work on all the links, but I have no idea how to add more var 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 tried adding this to the code but it does not work.
var navpill = pill.querySelector(".navpill");
navpill.classList.toggle("active");
If possible I would also like a way of clearing what has been done when clicked on the next submenu.
If I use the code above. It stays open when I click on the second link and then they are both open. I want the first one to close if the second is clicked.
onmouseoverevent to everynavpillwithdocument.querySelectorAllas you did withpills. no need to place it inside thepill.onclickevent. do it separately