This blog will explain the methods to hide buttons in JavaScript.
How to Hide Button in JavaScript?
To hide a button in JavaScript, the following methods can be utilized:
The mentioned approaches will now be discussed one by one!
Method 1: Hide Button in JavaScript Using “style.visibility” Property
The “style.visibility” property sets the visibility of an element. This property can be utilized to hide the visibility of the predefined button by referring to its “id”.
Syntax
Here, the visibility of the specified “Object” is set as “hidden”.
Check out the following demonstration for a better understanding.
Example
First, create a button using the input tag, assign it a value named “Click_Me”, and include an onclick which will trigger the “hideButton()” function when the added button is clicked:
In the JavaScript file, define the hideButton() function in such a way that it invokes the “document.getElementsById()” to access the created button and set its visibility as “hidden”:
document.getElementById('btn').style.visibility= 'hidden';
}
The output of the above program is shown as follows:
Method 2: Hide Button in JavaScript Using “style.display” Property
The “style.display” property sets the specified element’s display type. This technique can be implemented to hide the created button by fetching its specified id and setting “none” as its display type.
Syntax
Here, the display property of the “Object” is set as “none”.
Go through the following example for demonstration.
Example
We will utilize the same HTML code in this example. However, in the JavaScript file, we will define the “hideButton()” function which will be invoked when the button is clicked. In its definition, the “document.getElementById()” method will fetch the button using its “btn” id and the value of its “style.display” property will be set as “none” in order to hide it:
document.getElementById('btn').style.display= 'none';
}
Output
We have offered the simplest methods to hide buttons in JavaScript.
Conclusion
To hide a button in JavaScript, you can utilize the “style.visibility” and “style.display” properties. To do so, firstly, you have to fetch the button by specifying its id in the document.getElementbyId() method and then set the value of the style.visibility property as hidden, or none for the style.display property. This manual discussed the method related to hiding buttons in JavaScript.