How to Hide Button in Javascript
In this tutorial, you will learn how to hide button in javascript. The button
element is commonly used to submit form data to the server and there could be instances where you would like to toggle the visibility of the button
element. This is something that we are going to cover today.
There are multiple solutions for this problem, but I am going to share one of the straightforward solutions. We will leverage display
property to show or hide the button
element. This property is available for all the HTML elements.
In the following example, we have one checkbox. When the checkbox is checked, we will show our button and when it is unchecked, we will hide our button. Please have a look over the code example and the steps given below.
HTML & CSS
- We have a few elements in the HTML file and that includes
div
,button
,h1
,input
, andp
. Thediv
element with a class of container is just a wrapper for the rest of the elements. - We have some random text in the
paragraph
element. - The inner text for the
button
element is“Proceed”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <h1>Terms & Conditions</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit incidunt ipsum accusamus, nam hic numquam tempore recusandae quos at soluta fugit. Deleniti nesciunt voluptatem tempora laudantium omnis error dolorum quidem!</p> <div class="footer"> <div><input type="checkbox" checked><span>I Agree</span></div> <button>Proceed</button> </div> </div> <script src="script.js"></script> </body> </html>
.container { width: 50%; margin: auto; } p { border: 1px solid black; padding: 10px; } .footer { display: flex; justify-content: space-between; }
Javascript
- We have selected 2 elements
input
andbutton
usingdocument.querySelector()
method and stored them incheckbox
andbutton
variables respectively. - We have attached the
change
event listener to theinput
element. - In the event handler function, we are using
checked
property to verify whether the checkbox is checked or not. If it is checked, we will hide thebutton
element by setting thedisplay
property tonone
. - If the checkbox is unchecked, then we will show the
button
element with its default styles by setting thedisplay
property tonull
.
let checkbox = document.querySelector('input'); let button = document.querySelector('button'); checkbox.addEventListener('change', () => { if(!checkbox.checked) button.style.display = 'none'; else button.style.display = null; });