简体   繁体   中英

Hide a div onclick through javascript

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";
    }

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"
    }
}

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')" /> 

 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()" /> 

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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM