Ad

Why Can't I Use Javascript To Change The Visibility Property To Hidden

- 1 answer

I'm using javascript, so that when a user presses a button, a div will appear/disappear by changing the visibility property of the div. It works when the div is hidden and I want it to appear. However, when I presses the button again, it does not become hidden as it should.

document.getElementById("SmileyButton").addEventListener("click", getSmileys);

function getSmileys() {
  var button = document.getElementById("SmileyDiv").style.visibility = 'visible';
  // document.getElementById("SmileyDiv").style.visibility = 'visible';
  if (button.visibility == 'hidden') {
    button.visibility = 'visible'
  } else {
    button.visibility = 'hidden'
  }
}
.enterPostBackground {
  background-color: gainsboro;
  width: 400px;
  height: 50px;
}

#SmileyDiv {
  height: 80px;
  width: 160px;
  background-color: grey;
  overflow: scroll;
  visibility: hidden;
}
<br>
<br>
<div id="SmileyDiv"></div>
<div class="enterPostBackground">
  <button class="test" id="SmileyButton" style="font-size: 30px;float:left; " type="button" onclick="getSmileys()">&#128515</button>
</div>

Ad

Answer

This may solve your problem.

Changes I did,

  1. I removed the onclick from the button. You don't need it as long as you have registered the click event in the JavaScript side.
  2. I fixed your HTML as you had incorrect markup. _(You forgot to close the <script> tag, as well you forgot to close the second div tag.
  3. I change the logic of your script to make it more performant.

<!DOCTYPE html>
<html>
<head>
      <style>
          .enterPostBackground {
              background-color: gainsboro;
              width: 400px;
              height: 50px;
          }

          #SmileyDiv {
              height: 80px;
              width: 160px;
              background-color: grey;
              overflow: scroll;
              visibility: hidden;
          }

      </style>
</head>

<body>
    <br>
    <br>
    <div id="SmileyDiv"></div>
    <div class="enterPostBackground">

        <button 
            class="test" 
            id="SmileyButton" 
            style="font-size: 30px;float:left;"
            type="button"
          >&#128515</button>
     </div>
</body>
</html>
<script>
// I get the SmileyDiv here. This is because it runs only once, and makes 
// your script more performant.
var button = document.getElementById("SmileyDiv");
document.getElementById("SmileyButton").addEventListener("click", getSmileys);

// I set the initial visibility status here
button.style.visibility = 'visible';

function getSmileys() {
    // You had forgot to add the `.style` in the button property. That's 
    // why the button didn't worked properly.
    if (button.style.visibility === 'hidden') {
        button.style.visibility = 'visible'
    } else {
        button.style.visibility = 'hidden'
    }
}
</script>

Ad
source: stackoverflow.com
Ad