Search code examples
javascripthtmlcssdrop-down-menumenuitem

How to add mutually exclusivity on toggling dropdown menu


I have a menu with dropdown submenus. I'm trying to close an item when clicking on another, so that I don't have multiple items open at the same time. In a previous question: How to Apply .nextElementSibling to the next item of a dropdown menu a user suggested that I take a look at the function called mutually exclusivity. How can I add it to my menu?

var dropdownBtn = document.querySelectorAll('.menu-btn');

dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
  var menuContent = this.nextElementSibling;
  menuContent.classList.toggle("show");
  
}));
.menu-btn {
  background: #e0e0e0;
  padding: 10px;
  margin: 5px 0px 0px 0px;
}

.menu-btn:hover {
  background: #000;
  color: #fff;
}


.drop_container {
   display: none;
   background-color: #017575;
   transition: 0.3s;
   opacity: 0;
}

.drop_container.show {
  display: contents;
  visibility: visible;
  opacity: 1;
}

.drop_container > .item {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  padding: 10px 0px 0px 0px;
}
<div class="dropdown-menu">

<div class="menu-btn">One</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div>

<div class="menu-btn">Two</div>
<div class="drop_container">
  <a class="item" href="#">Contact Us</a>
  <a class="item" href="#">Visit Us</a>
</div>

</div>


Solution

  • Store previously clicked menu in a variable, and clear it's class if another menu was clicked

    var dropdownBtn = document.querySelectorAll('.menu-btn'),
        lastOpened = null;
    
    dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
        var menuContent = this.nextElementSibling;
        menuContent.classList.toggle("show");
    
        if (lastOpened && lastOpened !== menuContent)
          lastOpened.classList.remove("show");
    
        lastOpened = menuContent;
      
    }));
    .menu-btn {
      background: #e0e0e0;
      padding: 10px;
      margin: 5px 0px 0px 0px;
    }
    
    .menu-btn:hover {
      background: #000;
      color: #fff;
    }
    
    
    .drop_container {
       display: none;
       background-color: #017575;
       transition: 0.3s;
       opacity: 0;
    }
    
    .drop_container.show {
      display: contents;
      visibility: visible;
      opacity: 1;
    }
    
    .drop_container > .item {
      display: flex;
      flex-direction: column;
      margin-left: 10px;
      padding: 10px 0px 0px 0px;
    }
    <div class="dropdown-menu">
    
    <div class="menu-btn">One</div>
    <div class="drop_container">
      <a class="item" href="#">Contact Us</a>
      <a class="item" href="#">Visit Us</a>
    </div>
    
    <div class="menu-btn">Two</div>
    <div class="drop_container">
      <a class="item" href="#">Contact Us</a>
      <a class="item" href="#">Visit Us</a>
    </div>
    
    </div>