It's just semantics.
It is recommended that you use native HTML buttons using <button>
tag. However, if you are having custom controls using <a>
or <div>
tags, the following information on the role='button'
is highly recommended.
- Trigger a Response
If you are building custom controls, they should work just like a button. If you click the element, it should trigger a response. For example, This response isn't changing the text of the button i.e. custom control. If it is, then it is not a button.
- Keyboard focus
These custom controls acting as buttons should be focusable by tabbing through a keyboard and also should be focusable programmatically for screen-readers, so you need to add tabindex="0"
.
- Operability
The custom control should implement onclick
as well as onkeydown
events.
Buttons (and links) can be activated through Space and Enter. Hence, if you are adding the role to a custom control, you need to handle these events yourself. Else, the semantic loses its meaning. A screen-reader user will expect to activate the button using Space, but cannot.
The standard syntax for a custom control with the role='button'
is
<div role="button" tabindex="0" onClick="click_handler()" onkeydown="keyhandler_for_space_and_enter()">
The tabindex="0"
and onkeydown
are not necessary if you are using <a>
tag, but is required if you are using a non-focusable tag like <span>
or <div>
to manually allow focus.
Another useful tip is if you are still resorting to build custom button, it is much better to use <a>
tag since you can avoid onclick
handlers.