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

174
Vistas
is there a way to make a button cause a div to appear on the first click then disappear on the second click?

I wonder if there is a way for the same button to make a div appear if I click on it once and disappear if I click on it another time JS code:

const button = document.getElementById("menu");
const menu = document.querySelector(".box");
button.addEventListener("click", function () {
  menu.style.display = "block";
});

HTML code:

<button id="menu">click me for menu!</button>
<div class="box"></box>

CSS code:

.box{
  height: 200px;
  width: 200px;
  display: none;
}

I used this method before but I don't know if there is a way to use it directly

let clicks = 0;
button.addEventListener("click", function () {
  checkclicks();
  if (clicked === true) menu.style.display = "block";
  if (clicked === false) menu.style.display = "none";
});
function checkclicks() {
  clicks += 1;
  if (clicks % 2 === 1) {
    //on
    clicked = true;
  }
  if (clicks % 2 === 0) {
    //off
    clicked = false;
  }
}

EDIT I want it to be hidden by default and only appearing when I click on the button and gets hidden again when I click on the same button

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

0

You can use classList.toggle to toggle hidden class to your div with each click

    var mydiv = document.querySelector("#mydiv")
    var mybtn = document.querySelector("#mybtn")

    mybtn.addEventListener("click", function () {
       mydiv.classList.toggle("hidden")
    });
.hidden{
display:none;
}

#mydiv{
height:50px;
width:50px;
color:white;
background-color:blue;
padding:10px;
}
<div id="mydiv" class="hidden">test</div>
<button id="mybtn">Click Me!</button>

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