Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda