Toggle button design pattern: <a> element

This toggle button is created using the <a> 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 <a> element as a button through its accessibility API. This information is utilised by assistive technologies to inform users what they're dealing with.

Keyboard focus is handled by the browser because <a> is an interactive element.

Keyboard interaction is handled by the browser and through scripting. The <a> element can be activated with the Enter key and the button inherits this behaviour. The ability to activate the button using the space key is provided through scripting.

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.