We are about to commit a cardinal sin. Let's make a button:
<div class="button" onclick="someFunction()">Click Me</div>
Our button works if users click it with a mouse. But it is not keyboard accessible. Even if we add tabindex="0"
, which would make the <div>
focusable, users who use a keyboard to navigate our site will not at all be able to click our button.
If we instead used a regular <button>
element, it would be keyboard accessible. Try it out for yourself if you're on a keyboard:
<button onclick="clicked(this)">Good Button</button>
<div onclick="clicked(this)" tabindex="0">Bad Button</div>
false
function clicked(element) {
element.innerHTML = "You clicked me!"
}
Browsers come bundled with a bunch of accessibility options. Whether that's something complicated like a screen reader or something simple like allowing the user to zoom in, browsers make our lives as developers a lot easier.
So why then do browsers not make our above button keyboard accessible? Because accessibility should not be the responsibility of the browser.
I get it. The default <button>
styles suck and it's easier to style a <div>
. But a <button>
is the more accessible choice.
But I do think there is an argument to be made. Perhaps browsers should detect elements with an onclick
event (or something similar) and automatically treat it as a button.
I can already think of a few problems...for example:
<div class="button" onclick="someFunction()" onKeyDown="someOtherFunction()">Click Me</div>
Now, this fake button behaves differently if you're using keyboard input:
<div onclick="someFunction(this)" onKeyDown="someOtherFunction(this)" tabindex="0">Click Me</div>
false
function someFunction(element) {
element.innerHTML = "You clicked me!"
}
function someOtherFunction(element) {
element.innerHTML = "You pressed me with a keyboard!"
}
This is a rather simple case, but the point is, it's these countless needless considerations that would make things needlessly complicated. It's just easier to, as a developer, be responsible for your own software.