Toggle Component
Axiom01's toggle component provides a visually distinct and accessible switch for binary choices (on/off, true/false). It's built on native HTML checkbox inputs, ensuring robust functionality and accessibility.
Live Example
Basic Toggle
Checked Toggle
Disabled Toggle
Toggle with Icon
HTML Structure
The toggle component uses a hidden checkbox input and a styled label to create the switch appearance.
<div class="toggle-switch">
<input type="checkbox" id="toggle-basic">
<label for="toggle-basic">Enable Feature</label>
</div>
Styling
The .toggle-switch container wraps the native checkbox and its label. The checkbox itself is visually hidden, and the label is styled to resemble a switch.
.toggle-switch: Main container for the toggle.- The
<input type="checkbox">is styled to be visually hidden but remains functional. - The
<label>element is transformed into the visual toggle switch, with pseudo-elements (::before,::after) creating the track and thumb. - The
:checkedpseudo-class on the input drives the visual change of the toggle. - The
:disabledattribute on the input applies appropriate visual styles.
JavaScript Integration
The toggle component is primarily CSS-driven. JavaScript is generally not required for basic functionality, as the native checkbox handles state changes. However, you might use JavaScript to:
- Read or set the state of the toggle.
- Trigger actions based on the toggle's state change.
Accessibility
The toggle component is built with accessibility in mind:
- It uses a native
<input type="checkbox">, which is inherently accessible to screen readers and keyboard navigation. - The
<label>is correctly associated with the input usingforandidattributes, ensuring clicking the label toggles the checkbox. - For custom styling, the checkbox is visually hidden but remains in the DOM and accessible to assistive technologies.
- Consider adding
role="switch"to the input for enhanced semantic meaning for screen readers.
Customization
Customize the appearance using Axiom01's CSS variables for colors (e.g., --a-color-primary for the active state, --a-color-outline for the track), spacing, and animation speed. You can adjust the size, shape, and transition of the toggle switch to match your theme.