In this post, we will learn how to show or hide a div with a click of a button using JavaScript.
To show or hide a div in HTML we usually change the display attribute of the DOM element by using the CSS display property and setting it to display:block or display:none.
In JavaScript, we will be using the same block and none display property to manipulate the DOM to hide and show the div using Object.style.display
.
So let’s see an example to toggle the display property of a div using JavaScript.
Show and Hide div on button click
Consider the HTML markup below:
<body>
<div id="main-wrapper">
<p>
This is a static template, there is no bundler or bundling involved!
</p>
</div>
<button id="toggle-btn">Hide/Show</button>
<script src="script.js"></script>
</body>
Here we have <div>
with an id main-wrapper and a <button>
with and id toggle-btn.
So to display and hide the div we will add a click event listener to the <button>
to change the display attribute from default( i.e block) to none.
Let’s see the script code to perform the action.
const wrapper = document.getElementById("main-wrapper");
const btn = document.getElementById("toggle-btn");
btn.addEventListener("click", toggleDisplay);
function toggleDisplay() {
if (wrapper.style.display !== "none") {
wrapper.style.display = "none";
} else {
wrapper.style.display = "block";
}
}
In the JS code, we have first targeted the < div > and the toggle < button > using getElementById()
method.
Now we have added a click event listener to the button so that when the button is clicked it will run the toggleDisplay()
function.
In toggleDisplay() function, we have a condition wrapper.style.display !== "none"
that checked if the display style of the div is not equal to none (i.e block).
If the condition is true, i.e the display attribute is set to none (Hide the div in the page) else it is set to block (Show the div in the web page).
DEMO
Related Topics: