We can use JavaScript to show and hide a div using one button by combing the getElementById() method, the display property, and an if else conditional statement.
var displayStatus = document.getElementById("someDiv");
if ( displayStatus.style.display == 'none' ){
displayStatus.style.display = 'block';
} else {
displayStatus.style.display = 'none';
}
We can use JavaScript to show a div and hide a div, but to be able to toggle between the two, we can do so using the code above.
Let’s say we have the following html:
<div id="div1">This is a hidden div that we can show with JavaScript</div>
If we want to use JavaScript to show hide the div, we can do so by targeting the element’s display property. We do this simply by getting the id of the div and then changing its display property to “block” if it is hidden, or “none” if it is shown. We check this with an if-else conditional statement.
var displayStatus = document.getElementById("div1");
if ( displayStatus.style.display == 'none' ){
displayStatus.style.display = 'block';
} else {
displayStatus.style.display = 'none';
}
Note that we can also show/hide (or toggle) a div easily using jQuery with the toggle() method.
Using JavaScript to Show/Hide a Div With a Click
We can use JavaScript to show/hide a div very easily by combining the display property and an if-else conditional statement with an onclick event.
Let’s say that we have the following HTML where we want to give the user the ability to show and hide the div #div1. The div will just be a greenish box that will be shown to start.
Here is the HTML code:
<style>#div1 { width: 300px; height: 200px; background: #7bbfa2; }</style>
<div>
<div id="div1"></div>
<div class="click-me" onclick="toggleDiv()">Show/hide div</div>
</div>
In the JavaScript code, we will add an onclick event to a button that will run a function we will create. In the function, we will simply change the display property of the div to “block” if it is hidden, or “none” if it is shown.
Here is the JavaScript code:
function toggleDiv(){
var displayStatus = document.getElementById("div1");
if ( displayStatus.style.display == 'none' ){
//If the div is hidden, show it
displayStatus.style.display = 'block';
} else {
//If the div is shown, hide it
displayStatus.style.display = 'none';
}
};
The final code and output for this example of using JavaScript to show/hide a div with a click is below:
Code Output:
Full Code:
<style>#div1 { width: 300px; height: 200px; background: #7bbfa2; }</style>
<div>
<div id="div1"></div>
<div class="click-me" onclick="toggleDiv()">Show/hide div</div>
</div>
<script>
function toggleDiv(){
var displayStatus = document.getElementById("div1");
if ( displayStatus.style.display == 'none' ){
displayStatus.style.display = 'block';
} else {
displayStatus.style.display = 'none';
}
};
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to show and hide a div.
Leave a Reply