Sometimes, we want to create a toggle button with JavaScript.
In this article, we’ll look at how to create a toggle button with JavaScript.
How to create a toggle button with JavaScript?
To create a toggle button with JavaScript, we can toggle the className
of a button.
For instance, we write
<input
type="button"
id="btn"
value="button"
class="off"
onclick="toggleStyle(this)"
/>
to set onclick
to call toggleStyle
with this
element.
Then we define toggleStyle
by writing
function toggleStyle(el) {
if (el.className === "on") {
el.className = "off";
} else {
el.className = "on";
}
}
In it, we check if className
of the el
element is 'on'
.
If it is, then we set it to 'off'
.
Otherwise, we set it to 'on'
.
Then we add the styles for both classes by writing
.on {
border: 1px outset;
color: #369;
background: #efefef;
}
.off {
border: 1px outset;
color: #369;
background: #f9d543;
}
Conclusion
To create a toggle button with JavaScript, we can toggle the className
of a button.