Home > Software engineering >  is there a way to make a button cause a div to appear on the first click then disappear on the secon
is there a way to make a button cause a div to appear on the first click then disappear on the secon

Time:08-29

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

CodePudding user response:

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" >test</div>
<button id="mybtn">Click Me!</button>

  • Related