This blog will describe the method to create a simple toggle button in JavaScript.
How to Make a Simple Toggle Button in JavaScript?
To make a simple toggle button, use the simple conditional logic with the “value” attribute to change the state or value of the button.
Example 1: Toggling the Button’s State
In an HTML file, create a button and attach an “onclick” event that will call the function on a button click:
Define a function “toggle()” in JavaScript file or the <script> tag that will trigger on the button click:
{
var button = document.getElementById("btn");
if(button.value == "Accept")
{
button.value = "Reject";
}
elseif(button.value == "Reject")
{
button.value = "Accept";
}
}
In the above-defined function:
- First, get the button reference using its assigned id with the help of the “getElementById()” method.
- Use the conditional statement and change the value or state of the button. Set the value to “Reject” if it is equal to “Accept”.
- If the button’s value is “Reject”, set it to “Accept”.
Output
Example 2: Toggling the Button’s State With Color
You can also toggle the style with the value of the button using the “style” attribute:
{
var button = document.getElementById("btn");
if(button.value == "Accept")
{
button.value = "Reject";
document.getElementById("btn").style.background = "red";
}
elseif(button.value == "Reject")
{
button.value = "Accept";
document.getElementById("btn").style.background = "yellow";
}
}
As you can see in the output, the button changes its value and color on the button click:
Example 3: Toggling the Text
Here, we will toggle the text on the button click. In an HTML file, first, create a button and a text using <p> tag that will not be displayed on the page:
<input type = "button" id="btn" onclick="toggle()" value="Welcome">
Define a function that will show the text on the web page by clicking on the button:
{
var text = document.getElementById("welcome");
if (text.style.display === 'none') {
text.style.display = 'block';
}else {
text.style.display = 'none';
}
}
Output
We have gathered all the essential information related to creating a simple toggle button in JavaScript.
Conclusion
For creating a simple toggle button, use the conditional logic statements with the “value” attribute to change the state or value of the button. A toggle button is a useful UI element that can help improve the functionality and usability of JavaScript applications. This blog described the procedure to create a simple toggle button in JavaScript with detailed examples.