0

I have a java script function:

function showPrerequisites() {
    var x = document.getElementById('prerequisites');
    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

With a div and a button:

<button class="show-prerequisites" onclick="showPrerequisites()">Show/Hide Prerequisites</button>
<div class="prerequisites" id="prerequisites">

This works fine and the div gets hidden and shown as expected, however, I want to make the div hidden by default, so I added display: none; to my CSS getting:

.prerequisites {
  background-color: #ededed;
  margin : 20px auto;
  border: solid #e6e6e6 thin;
  border-radius: 5px;
  padding: 3%;
  font-weight: 300;
  display: none;
}

When I do that, pressing the button for the first time doesn't show the div, I have to press it twice in order to show it. What am I doing wrong?

1 Answers1

1

function showPrerequisites() {
    var x = document.getElementById('prerequisites');
    var style = window.getComputedStyle(x);
    var display = style.getPropertyValue('display');
    
    if (display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}
.prerequisites {
  background-color: #ededed;
  margin : 20px auto;
  border: solid #e6e6e6 thin;
  border-radius: 5px;
  padding: 3%;
  font-weight: 300;
  display: none;
}
<button class="show-prerequisites" onclick="showPrerequisites()">Show/Hide Prerequisites</button>
<div class="prerequisites" id="prerequisites">
qiAlex
  • 4,290
  • 2
  • 19
  • 35