Switch Example Using HTML Button

About This Example

This example illustrates implementing the Switch Pattern with an HTML button as a switch element and using an SVG element to provide graphical rendering of switch states. It also demonstrates using the group role to present multiple switches in a labeled group.

Similar examples include:

Example

Environmental Controls

Accessibility Features

Keyboard Support

Key Function
Tab
  • Moves keyboard focus to the switch.
Space, Enter
  • Toggle switch between on and off.

Role, Property, State, and Tabindex Attributes

Role Attribute Element Usage
switch button Identifies the button element as a switch.
aria-checked="false" button
  • Indicates the switch is off.
  • CSS attribute selectors (e.g. [aria-checked="false"]) are used to synchronize the visual states with the value of the aria-checked attribute.
aria-checked="true" button
  • Indicates the switch is on.
  • CSS attribute selectors (e.g. [aria-checked="true"]) are used to synchronize the visual states with the value of the aria-checked attribute.
aria-hidden="true" span.on and span.off
  • Removes the strings on and off that appear to the right of the switch from the accessible name of the switch.
  • These strings are included only for enhancing visual comprehension of the state; element states are not permitted in accessible names.
h3 Provides a grouping label for the group of switches.
group div Identifies the div element as a group container for the switches.
aria-labelledby div References the h3 element to define the accessible name for the group of switches.

JavaScript and CSS Source Code

HTML Source Code

To copy the following HTML code, please open it in CodePen.