2

All the stuff for the button seems right and it works in reverse of what I want currently. when I load the page the div: myDIV is there and the button toggles it disappearing and reappearing. How do I make myDIV none by default but still have the button function as a toggle

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
  display:none;
}
</style>
</head>
<body>


<button onclick="myFunction()">test</button>

<div id="myDIV">
This is my DIV element.
</div>



<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

</body>
</html>

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Semajx3
  • 23
  • 4
  • add style `display:none` to div chartContainer – Serene Abraham Mathew Mar 23 '19 at 08:28
  • I have already tried that and it just means that I have to click the button twice for the div to appear :) – Semajx3 Mar 23 '19 at 08:31
  • where is button toggles it disappearing and reappearing? – Hien Nguyen Mar 23 '19 at 08:32
  • 1
    This is not a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – Andy Hoffman Mar 23 '19 at 08:34
  • 1
    so, you made ` – Jaromanda X Mar 23 '19 at 08:51
  • even when I have this simplified version I have the problem of having to click the button twice to display myDIV initially [jsfiddle](https://jsfiddle.net/gquxwodj/) – Semajx3 Mar 23 '19 at 09:01

2 Answers2

0

I think the point is in here style.display = '' actually do

When you use style.display to get display status, it can not get display attribute defined in css

Rey Wang
  • 87
  • 7
0

You need to get CSS Value first to toggle the display value with a button in JS. By default, it is advised not to give inline style on HTML.

function myFunction() {
 const cont = document.querySelector("#chartContainer");
 const styles = getComputedStyle(cont)
  const displayStyle = styles.display;
  if(displayStyle === "none"){
   cont.style.display = "block";
  }else {
   cont.style.display = "none";
  }
  
}

const BTN = document.querySelector("button");
BTN.addEventListener('click', myFunction);
.container {
  background-color: #FFF;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
}

#chartContainer {
  background-color: blue;
  border-radius: 25px;
  height: 200px;
  width: 100%;
  float: below;
  display: none;
}

button {
  width: 50px;
  height: 50px;
}
<div class="container">
    <button>toggle</button>
    <div id="chartContainer">
    </div>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
</div>
Emilie
  • 21
  • 3