0

I have done for showing a div on click i want to remove on another click. I want the div to be removed on another click.

Here is the HTML code

<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
    <input type="button" name="answer" value="Show Div" onclick="showDiv()" />

Javascript

 function showDiv() {
       document.getElementById('welcomeDiv').style.display = "block";
    }
haMzox
  • 2,073
  • 1
  • 12
  • 25
J. Shabu
  • 1,013
  • 9
  • 22

4 Answers4

0

You have to check the visibility of the div and do a toggle based on that.

 function showDiv() {
    if( document.getElementById('welcomeDiv').style.display == "none") {
       document.getElementById('welcomeDiv').style.display = "block";
    }
    else {
       document.getElementById('welcomeDiv').style.display = "none"
    }
}
Avitus
  • 15,640
  • 6
  • 43
  • 53
0

Get rid of the inline styling and use a class to toggle the display type. This is cleaner and you can easily reuse it for other elements.

function showDiv(element) {
  document.querySelector(element).classList.toggle("invisible");
}
.invisible {
  display: none;
}
<div id="welcomeDiv" class="answer_list invisible"> WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv('#welcomeDiv')" />
Christoph
  • 50,121
  • 21
  • 99
  • 128
0

function showDiv() {
  var element = document.getElementById('welcomeDiv');
    if(!element.classList.contains('show')){
    element.classList.add('show');
    } else {
    element.classList.remove('show');
    }
       
       
 }
.show {
   display: block !important;
}
<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
    <input type="button" name="answer" value="Show Div" onclick="showDiv()" />
sumit chauhan
  • 1,270
  • 1
  • 13
  • 18
0

Check for the current visibility of the DIV and let the javascript function do accordingly.

function showDiv() {
    if( document.getElementById('welcomeDiv').style.display == "none") {
       //If it is not visible, make it visible
       document.getElementById('welcomeDiv').style.display = "block";
    }
    else {
       //Else, make it invisible.
       document.getElementById('welcomeDiv').style.display = "none"
    }
}
bonyem
  • 1,148
  • 11
  • 20