Sometimes, we want to disable an HTML button after one click with JavaScript.
In this article, we’ll look at how to disable an HTML button after one click with JavaScript.
Disable an HTML Button After One Click with JavaScript
To disable an HTML button after one click with JavaScript, we can call the jQuery one
method on an element to attach an event handler that emits once only.
We can also call addEventListener
with the once
option set to true
if we want to use plain JavaScript.
For instance, we can write:
<button>
click me
</button>
to add a button.
Then we call one
by writing:
$('button').one('click', () => {
$('button').attr('disabled', 'disabled');
});
We call one
with 'click'
to listen to the click event on the button once.
The callback sets the disabled
attribute of the button to true
.
We can do the same thing with plain JavaScript by writing:
const button = document.querySelector('button');
button.addEventListener("click", () => {
button.setAttribute('disabled', 'disabled')
}, {
once: true
});
We get the button with document.querySelector
.
Then we call addEventListener
on the button
with 'click'
to add a click listener to it.
And we call setAttribute
to set the disabled
attribute value in the callback.
In the 3rd argument, we set once
to true
to make the event only emit once.
Conclusion
To disable an HTML button after one click with JavaScript, we can call the jQuery one
method on an element to attach an event handler that emits once only.
We can also call addEventListener
with the once
option set to true
if we want to use plain JavaScript.