Search code examples
javascripthtmlcssshow-hide

Hide div after showing it with javascript


I'm using javascript to show a hidden div by clicking a button. After the div is displayed, I want to be able to click the button again and hide the div, and so on...

Here is my javascript:

<script type="text/javascript">
function showDiv() {
   document.getElementById('dropdownText').style.display = "block";
}
</script>

This is the button:

<input type="button" name="answer" value="+" onclick="showDiv()" />

This is the hidden div:

<div id="dropdownText" style="display:none;">
   This is the dropdown text.
</div>

Solution

  • You can e.g. bind specified class to the element and just toggle it.

    function showDiv() {
       document.getElementById('dropdownText').classList.toggle("hidden");
    }
    .hidden {
      display: none;
    }
    <input type="button" name="answer" value="+" onclick="showDiv()" />
    This is the hidden div:
    
    <div id="dropdownText" class='hidden'>
       This is the dropdown text.
    </div>