On button click hide and show div using JavaScript:
In this post, we will learn how to hide and show a div
with a button click in JavaScript
. We will add one onClick
listener to the button and we will toggle the visibility of the div
in that listener.
We will use the CSS display
properties block
and none
to show and hide a div
.
CSS display property:
The display
property of CSS can be used to change the display type. We will use the block
and the none
properties. The block
property will generate a block element box and the none
property will remove the element box from the DOM.
Let’s consider the below example:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#first {
display: block;
}
#second {
display: none;
}
</style>
</head>
<body>
<div id="first">Hello World</div>
<div id="second">Second Hello World</div>
</body>
</html>
- It is showing two
<div>
components. The ids of these components arefirst
andsecond
. - In the
CSS
style sheet,display: block
style is applied to the firstdiv
anddisplay: none
is applied to the seconddiv
.
So, we can change the display
property of a div to change its visibility.
JavaScript program to show and hide a div on clicking a button:
We need to get the reference of a <div>
component to change its display
property. The following program shows how to toggle the visibility of a <div>
component programmatically with JavaScript
:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function toggleVisibility() {
const div = document.getElementById("first");
div.style.display = div.style.display === "none" ? "block" : "none";
}
</script>
</head>
<body>
<div id="first">Hello World</div>
<div id="second">Second Hello World</div>
<br />
<button onclick="toggleVisibility()">Click me</button>
</body>
</html>
-
Download it on Github
-
We added a
button
. On clicking the button, it calls thetoggleVisibility
method. -
In
toggleVisibility
, we are changing thedisplay
property of the div with idfirst
. If thedisplay
value isnone
, it changes it toblock
and vice versa.
How to change the visibility of different div with the same method:
We can get the id of a div
as the parameter and change the visibility of that div
with the same method.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function toggleVisibility(id) {
const div = document.getElementById(id);
div.style.display = div.style.display === "none" ? "block" : "none";
}
</script>
</head>
<body>
<div id="first">First div</div>
<div id="second">Second div</div>
<div id="third">Third div</div>
<br />
<button onclick="toggleVisibility('first')">1st div</button>
<button onclick="toggleVisibility('second')">2nd div</button>
<button onclick="toggleVisibility('third')">3rd div</button>
</body>
</html>
- Download it on Github
Here, the toggleVisibility
method takes the id
as its parameter and changes the visibility for the item with the given id
. We added three buttons to handle the visibility for the first, second and third div
.