How to show or hide a div when clicking on the same button?

I face a problem when i want to add interactivity on my leaflet map.

I have a button on my map

<button id="az">Availability Zones</button>

The thing i want is when i click on it, it show a square of informations on my map So i have create a square

<div class="square" id='square'> </div> 
CSS = .square{
  z-index: 4000;
   width: 100%;
  height: 0;
  padding-top: 100%;
  background-color: #ccc;
  position: absolute;
  display: none;
}

And an other css class square with same properties but with a display: block

.squareclick{
  z-index: 4000;
   width: 30%;
  weight: 30%;
  padding: 0 25 30;
  margin-left: 400px;
  margin-bottom: 200px;
  height: 0;
  padding-top: 100%;
  background-color: #ccc;
  position: relative;
  display: block;
}

Now, for opening this square on a button i’ve add some interactivity

var button = document.getElementById('az')
L.DomEvent.on(button,'click',function(e){
    console.log('Button clicked')
});

L.DomEvent.on(button,'click',function(){
    document.getElementById('square').setAttribute("class", "squareclick");
  
});

The thing is that that button works for opening the square, but not for closing (I know this is normal) I’ve try that thing but it seems to not work

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }

I don’t know how to add a second interactivity on the same button ๐Ÿ™

If someone can help! Thank you very much

Answer

What you can try doing is instead of directly checking whether the square is visible or not, you can set a variable to check. Change:

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

To:

var shown = false;    

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (shown == false) {
    x.style.display = "block";
    shown = true;
  } else if (shown == true) {
    x.style.display = "none";
    shown = false;
  }
}

The variable shown tells us at the start the square is not visible. Every time you click the button, the variable changes and so does the style. If the square was to be visible at the start, then you can simply change shown to true at the start of the script. See if that way works. ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *