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

323
Vistas
Hiding navigation after clicking somewhere esle not working correctly

I have a burger nav. After clicking the burger sidebar nav shows up and hides after clicking once more. I want to make it so I don't have to click the burger button, but I can click somewhere else (main container, etc.) and hide the sidebar. This is the burger button code:

function navBurger() {
    var element = document.querySelector(".navbar");
    var burger = document.querySelector(".burger-btn");
    element.classList.toggle("extended");
    burger.classList.toggle("open");
}

This part works just fine, but when I add this:

window.onclick = function() {
    var element = document.querySelector(".navbar");
    var burger = document.querySelector(".burger-btn");
    
    if (element.classList.contains("extended")) {
        window.onclick = function() {
            element.classList.remove("extended");
            burger.classList.remove("open");
        }
    } 
}

Navigation will hide after the first click, but I am not able to show and then hide it after that first click. It's like the script thinks that navigation still has that class (but it was removed) and won't let the navbar be opened. Is there a way to solve this?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In your original code, after clicking the first time to open the nav, the window onclick would then remove the classes added by clicking on the menu button as the event bubbled up. To fix this, add event.stopPropagation() to your menu click handler.

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

I also removed the re-bind of the onclick handler, as it was causing the first click to not close the menu properly.

function navBurger(e) {
    console.log('button clicked')
    var element = document.querySelector(".navbar");
    var burger = document.querySelector(".burger-btn");
    element.classList.toggle("extended");
    burger.classList.toggle("open");
    // Prevents the window onclick from firing after this function runs
    // try commenting this out
    e.stopPropagation();
}

window.onclick = function() {
    console.log('onclick triggered');
    var element = document.querySelector(".navbar");
    var burger = document.querySelector(".burger-btn");
    
    if (element.classList.contains("extended")) {
        element.classList.remove("extended");
        burger.classList.remove("open");
    } 
}

document.querySelector(".burger-btn").addEventListener("click", navBurger);
.navbar.extended {
  background: green;
}

.burger-btn.open::after {
  content: "Open";
  display: inline;
}
<nav class="navbar"><button class="burger-btn" type="button">Nav</button></nav>

about 4 years ago · Juan Pablo Isaza Denunciar

0

The cause of the problem is that the global click handler replaces itself with a nested, unconditional function to turn off the burger menu. A second click will open the menu but bubble up to the window handler and turn it off again.

The global handler needs to determine if the click is inside or outside the extended menu before turning it off. Applying the closest method to the click event target can help with this.

window.onload = function() {
    var element = document.querySelector(".navbar");
    var burger = document.querySelector(".burger-btn");
    window.onclick = function(event) {
        if( burger.classList.contains("open") 
          && !event.target.closest(".extended") ) {
            // the click is outside an open extended element
            element.classList.remove("extended");
            burger.classList.remove("open");
        }    
    };
};

The above should close the burger menu if the user clicks outside the element with class "extended". JQuery documentation covers the jQuery closest method and event.target if you wish to write the code in jQuery.

Note setting window.onclick is set in window.onload to avoid confusion, and that using oneventname properties of elements is better replaced by using addEventListener calls in JavaScript.

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