简体   繁体   中英

Hide other dropdowns when one is already open not working

Building a mega menu that mostly works. Last step I'm trying to achieve is when a user clicks on a mega menu item, it closes all other mega menus that are open.

Here's the JavaScript code I have below. The mega menu currently toggles correctly when clicking on each parent navigation link, but doesn't currently hide other mega menus when one mega menu is open.

const navLink = document.getElementsByClassName("menu-item-has-children");

// Loop over main navigation links
for (let i = 0; i < navLink.length; i++) {
  // Grab specific ID that each mega menu has
  const menuId = document.querySelector(`#${dropDownMenu[i].id}`);
  // On click of top nav items, toggle mega menu visibility (this works).
  navLink[i].addEventListener("click", () => {
    menuId.classList.toggle("display-on");
  });
  // If the mega menu is open (display-on class is active), then don't show the other mega menus.
  // (This does not work).
  return menuId.classList.contains("display-on")
    ? (menuId.style.display = "none")
    : "";
}

Link to live demo including HTML here if need be.

Thanks.

I have forked your example and simplified it. You can see the code here .

I make usage of Event Delegation . This allows you to handle all the click events (open dropdown, close dropdown via close button) in a single event handler (line 14 in the example) which is easier to read and maintain in my opinion.

The example does also close an already opened dropdown menu (see line 21 - 23).

I have also added an event handler to the document object to handle clicks outside of a dropdown to close it like you did.

Hope it solves your problem.

Best regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM