An HTML button is one of the few elements that has its own state. Along with almost all the form controls.
For example you want to only enable the button when a text input element is filled.
Or when a specific checkbox is clicked, like the ones you see to say “I read the terms and conditions”, something that no one actually reads.
Here’s how to do it.
You select the element, using
const button = document.querySelector('button')
If you have multiple buttons you might want to use
document.querySelectorAll() and loop through the results.
Anyway, once you have the element reference, you set its disabled property to
true to disable it:
button.disabled = true
To enable it back again, you set it to
false to enable it again:
button.disabled = false
More browser tutorials:
- What is the Doctype
- How to remove all CSS from a page at once
- The requestAnimationFrame() guide
- How to only accept images in an input file field
- The Complete Guide to Progressive Web Apps
- Mouse events