The Idea
<div>, <span>, and <a> elements are commonly misused as buttons. Why is this a problem? Why is this wrong?Accessibility Issues
Using the wrong HTML elements typically results in accessibility issues. Here are a couple reasons why using<div>
and <span>
elements will negatively impact accessibility when used in place of semantic elements:
- They aren't interpreted by assistive technologies any differently than plain text.
- They aren't inherently keyboard accessible.
<div>
and<span>
elements aren't tabable by default, and will require a keyboard-specific event to behave the same way as the click event.
Bad HTML Semantics
Here's what the W3C says about the<div>
, <span>
, and <a>
elements:
- div
-
"...has no special meaning at all…authors are strongly encouraged to view the
<div>
element as an element of last resort…use of more appropriate elements…leads to better accessibility for readers and easier maintainability for authors." - span
-
"The
<span>
element doesn't mean anything on its own..." - a (anchor)
-
I can use them for buttons, right? No.
<a>
elements are interpreted differently than plain text by assistive technologies. However, they're only in the tab order if it's got anhref
value. "If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents...[hyperlinks] are links to other resources..."
a11yButton Magic
It's actually not magic—a11yButton ensures your non-button elements behave more like a buttons. Here's what it does:- tabindex=0
- this attribute is set to 0, so the element is placed in the natural tab order
- role=button
- WAI-ARIA attribute applied to the element to identify it as a button to assistive technologies
- keypress
- event attached to the enter key (key 13) and space bar (key 32), which will trigger the element's 'click' handler
Using a11yButton
Assuming you starting with something like the "buttons" below. You can't use the keyboard to navigate/use them, and screen readers don't interpret the buttons like buttons—just plain text. Now apply a11yButton elements similar to those above.$('.good-button').a11yButton();
Now you're able to use the keyboard to access these buttons and most assistive technologies like screen readers will interpret them as buttons.