Skip to content Skip to sidebar Skip to footer

Toggle Menu With Javascript. Target Multiple Variables With 1 Click Function

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 t

Solution 1:

I think this is probably closer to what you want.

(It's unclear if you wanted the submenu items to be highlighted when they're clicked - currently, clicking them just collapses the menu anyway so you wouldn't see. Also I removed the hrefs because they aren't adding anything useful.)

var pills = document.querySelectorAll(".expand");
var subs = document.querySelectorAll(".submenu");

pills.forEach(function(pill) {
  pill.addEventListener("click", function() {
    var sub = pill.querySelector(".submenu");
    
    var alreadyOpen = false;
    if (sub.classList.contains("collapse")) alreadyOpen = true;
    
    pills.forEach(function(pill2) {
      pill2.classList.remove("active"); 
    });

    subs.forEach(function(sub2) {
      sub2.classList.remove("collapse"); 
    });

    if (!alreadyOpen) { 
      sub.classList.toggle("collapse");
      this.classList.add("active");
    }
  });
});
.expand.active {
  background-color: red;
}

.expand.active > .submenu
{
  background-color: #1f1f1f;
}

.mainmenu {
  background-color: #1f1f1f;
}

.navpill {
  padding: 15px;
  color: white;
}

.submenu {
  display: none;
}

.submenu.collapse {
  display: block;
}
<div><ulclass="mainmenu"><liclass="navpill expand">Link collapse 1
      <ulclass="submenu"><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li></ul></li><liclass="navpill expand">Link collapse 2
      <ulclass="submenu"><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li><liclass="navpill">sub Link 1</li></ul></li><liclass="navpill">no link</li><liclass="navpill">no link</li></ul></div>

Post a Comment for "Toggle Menu With Javascript. Target Multiple Variables With 1 Click Function"