Category: Vanilla Javascript

Added: 29th of December 2022

Viewed: 1,041 times

Related Tips & Tutorials

Get the window width and height in Javascript


Show and Hide div using 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>