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

175
Visualizações
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 Respostas
Responde à pergunta

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 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