ARIA Buttons demonstration

Published: November 26, 2016

Last updated: December 11, 2021

See source on GitHub

Pattern Demos

Using an <a href> as a base to make a button:

Do a thing

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:

Enable Dark Mode

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 a aria-disabled=true.
  • If a role=button also has an aria-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, a click() 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).

Continue reading