I am building a dropdown menu. As is, when I open one submenu, it stays open, even if I open a second submenu. When I open the second submenu, it should close any other open menus.
const submenuLinks = document.querySelectorAll('.has-submenu > a');
submenuLinks.forEach(element => element.addEventListener('click', function(e) {
var submenu = element.nextElementSibling;
if (submenu.classList.contains('menu-hide')) {
submenu.classList.add('menu-show');
submenu.classList.remove('menu-hide');
} else {
submenu.classList.add('menu-hide');
submenu.classList.remove('menu-show');
}
}));
.menu-hide {
display: none;
}
.menu-show {
display: block;
}
<nav>
<ul class="menu">
<li>
<a href="#">Menu Item 1</a>
</li>
<li class="has-submenu">
<a href="#">Menu Item 2 »</a>
<ul class="menu-sub menu-hide">
<li><a href="#">Submenu Item 1</a></li>
<li><a href="#">Submenu Item 2</a></li>
<li><a href="#">Submenu Item 3</a></li>
</ul>
</li>
<li class="has-submenu">
<a href="#">Menu Item 3 »</a>
<ul class="menu-sub menu-hide">
<li><a href="#">Submenu Item 1</a></li>
<li><a href="#">Submenu Item 2</a></li>
<li><a href="#">Submenu Item 3</a></li>
</ul>
</li>
</ul>
</nav>