JavaScript - Show and hide div on button click using JavaScript
This post is about how to show and hide a div on button click using JavaScript. We will change the CSS property of the element using JavaScript to hide and show the content.
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:
Related Posts
How to read text file in JavaScript (line by line)
This article is about how to read text file in JavaScript line-by-line from local computer using Html input field.
Get user location from browser using JavaScript
Tutorial on how to get user location like latitude and longitude from our browser using geolocation() function in JavaScript.
How to Get the ID of a Clicked Button or Element in JavaScript
Find out how to get the id of a button when clicked in JavaScript using onclick event listener and passing on the this.id or this.target.id.
JavaScript - How to export multiple functions from a file
In this article, we will be covering how we can export and import multiple functions in JavaScript.
