Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda