It is possible to disable a <button> element by setting the disabled attribute, for example with
document.querySelector("button").disabled = true;
However, this has some unfavourable usability implications such as causing the button to lose focus and become inaccessible via keyboard navigation. Some users will see the visual cue that the button is disabled, for example because something may be missing from the form. For users who rely on keyboard navigation and screen readers, this information will be much harder to get.
What is a good way to disable a button?
It is possible to make the button behave as if it were disabled without actually disabling it. You can use the
aria-disabledattribute to do this:Based on the
aria-disabledattribute, the styling of the button is changed so that you still get the visual cue that this button is inactive. In addition, the guard will only allow the action to be performed if thearia-disabledattribute is not true and the event hasn't already been prevented.Disabling a button will just be:
To improve usability, you might consider adding a tooltip to this disabled button, informing the user why the button is disabled. When adding the tooltip, be sure to help screen reader users by adding an
aria-liveelement.