ARIA Buttons demonstration
Published: November 26, 2016
Last updated: December 11, 2021
Pattern Demos
Using an <a href>
as a base to make a button:
Using a <span>
as a base to make a toggle button:
Bold Text
I'm some text
Using a <c-button>
custom element to make a toggle button:
Using a <span>
as a base for a disabled button:
Can't do anything
Pattern Details
Pattern Markup
<a id="test1" href="#" role="button">Do a thing</a>
<output></output>
<span id="test2" role="button" aria-pressed="false">
Enable a setting
</span>
<c-button id="test3" role="button" aria-pressed="false">
Enable Dark Mode
</c-button>
<span id="test4" tabindex="0" role="button" aria-disabled="true">
Can't do anything
</span>
This script simply runs through the DOM and looks for instances of role=button
and then does the following:
- If they lack a
tabindex
, one is assigned so the buttons are keyboard focusable, unless there is aaria-disabled=true
. - If a
role=button
also has anaria-pressed
attribute, then a toggle event is added to those buttons with an "click" event. - A
keydown
event listener is added to all the faux buttons. It ensures that Space and Enter keys will activate the button. If those keys are pressed, aclick()
is used to simulate the click event for the buttons.
You should really just use a <button>
element instead. You won't need the majority of this script then, and you'd get automatic Windows High Contrast Mode styling (which I have not done anything to provide for with these demos).