Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Recorra los elementos del menú desplegable para agregar clase al próximo hermano en Vanilla JS

Estoy aprendiendo JavaScript y estoy tratando de entender cómo crear un megamenú de navegación. Básicamente, cada botón tiene un div después que contiene el contenido del megamenú. Pasar el cursor O hacer clic en el botón agrega una clase al menú desplegable (también podría usar mostrar/ocultar dentro del JS, no estoy seguro de cuál es mejor). La clase agrega opacidad y visibilidad al div.

Creé una variable de "contenedor", por lo que solo escucha dentro de la barra de navegación y luego recorre los botones para agregar el oyente con nextElementSibling, pero parece que no puedo hacerlo funcionar.

Margen:

 <nav id="main-nav"> <div class="nav-content"> <div class="nav-item"> <button class="nav-dropdown">Services</button> <div class="nav-submenu"> (Links) </div> </div> <div class="nav-item"> <button class="nav-dropdown">Locations</button> <div class="nav-submenu"> (Links) </div> </div> <div class="nav-item"> <button class="nav-dropdown">About Us</button> <div class="nav-submenu"> (Links) </div> </div> </div> </nav>

JS:

 ( function() { // initiating vars var desktop, mobile, container; // Breakpoints desktop = window.matchMedia("(min-width: 769px)"); mobile = window.matchMedia("(max-width: 768px)"); // Target only navbar container = document.getElementById( 'main-nav' ); if ( ! container ) { return; } // Desktop dropdown click controls if (desktop.matches) { // only look for .nav-dropdown class const desktopParents = container.querySelectorAll(".nav-dropdown"); // get each instance of .nav-dropdown for (const desktopParent of desktopParents) { // if a button is clicked, add class to that button's dropdown only document.addEventListener('click', function(event) { // getting correct dropdownby targeting next sibling of button (div.nav-submenu) var dropdown = desktopParent.nextElementSibling; var desktopParent = desktopParent.contains(event.target); // adding and removing show dropdown class if (dropdown.classList.contains('nav-active')) { dropdown.classList.remove('nav-active'); } else { dropdown.classList.add('nav-active'); } }); } } }() );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su detector de eventos se adjunta a todo el documento, por lo que el evento se activa cuando alguien hace clic en cualquier parte de la página. Cambie el document a la variable de su botón desktopParent para que los eventos se activen cuando se haga clic en el botón. Puede hacer referencia al elemento de botón usando this dentro de la función de devolución de llamada del detector de eventos.

 desktopParent.addEventListener('click', function(event) { // getting correct dropdownby targeting next sibling of button (div.nav-submenu) var dropdown = this.nextElementSibling; var desktopParent = this.contains(event.target); ... }

Aquí hay un ejemplo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!