Toggle button design pattern: <span> element

This toggle button is created using the <span> element, with scripting to provide the expected behaviour. Additional semantic information is provided using ARIA.

It is better to use the <button> element to create a toggle button because the browser automatically provides keyboard support and most semantic information.




Uses the ARIA role attribute with a value of button. This informs the browser that it should expose the <span> element as a button through its accessibility API. This information is utilised by assistive technologies to inform users what they're dealing with.

Uses the HTML tabindex attribute with a value of 0. This places the button into the tab order based on its location in the source order. The visual appearance of the button changes when focus moves to it.

Keyboard interaction for the button is handled through scripting. Both enter and space key events are captured, and used to trigger the button's expected behaviour.

The aria-pressed attribute is used to indicate the state of the button. It is set to false initially, then scripted to toggle between true/false whenever the button is activated.

The visual appearance of the button when pressed (or not) is hooked onto the aria-pressed attribute using an intelligent CSS selector, instead of a class name. Although this does not affect accessibility, it creates a cleaner separation between structure and design.