Show and Hide div using Javascript
ID: 332
Category: Vanilla Javascript
Added: 29th of December 2022
Updated On: Tutorial updated and rechecked on 29th of October 2024
Views: 1,769
Related Tips & Tutorials
➔
Get the window width and height in Javascript
The Javascript below shows and hides a div on a webpage
Two input type buttons are created in HTML. Depending on what button the user clicks, the onClick event calls the Javascript functions showBox() or hideBox()
The showBox() function displays the div box1 by using the document method getElementById('box1') and style.display="block"
The hideBox() function removes the div box1 by using the document method getElementById('box1') and style.display="none"
The div id
box1 is styled using the css
.box1 class
<style>
.box1
{
width:150px;
height:100px;
padding:10px;
background:orange;
position:relative; top:30px;
display:none;
}
</style>
<script>
function showBox() {
document.getElementById('box1').style.display="block";
}
function hideBox()
{
document.getElementById('box1').style.display="none";
}
</script>
<input type="button" onClick="showBox();" value="Show Box">
<input type="button" onClick="hideBox();" value="Hide Box">
<div class="box1" id="box1">Click Me!!</div>
Click here to view example