data-switch
Transform a checkbox into a sliding toggle switch with optional size variants. Add data-switch to any checkbox for accessible on/off controls.
Overview
The data-switch attribute transforms a native <input type="checkbox"> into a sliding toggle switch. No wrapper element needed — just add the attribute directly to the checkbox.
How It Works
Add data-switch to any <input type="checkbox">. The init script:
- Sets
appearance: noneon the checkbox to remove native styling - Renders a track and sliding knob via CSS pseudo-elements
- Adds
role="switch"to the element for proper semantics - Responds to the
checkedstate with a slide transition - Sets
data-switch-initto prevent double-binding
The underlying checkbox remains a real form control. It submits with the form, supports validation, and fires native change events.
Attributes
| Attribute | Values | Description |
|---|---|---|
data-switch |
"", "sm", "lg" |
Transforms the checkbox into a toggle switch. Value sets the size variant (default: standard). |
data-switch-init |
boolean | Set automatically to prevent double-binding. Do not set manually. |
Size Variants
Three size variants are available via the attribute value: sm (small), default (empty string), and lg (large). The track and knob scale proportionally.
With Form Field
Wrap in <form-field> for validation feedback, helper text, and required indicators. The switch works seamlessly with form-field's validation lifecycle.
Checked by Default
Add the native checked attribute to render the switch in the on position initially.
Disabled and Read-only
Native disabled and readonly attributes are fully supported. Disabled switches are visually muted and non-interactive. Read-only switches display their current state but cannot be toggled.
Settings Group
Combine multiple switches in a <fieldset> for grouped settings panels.
Styling
The switch track and knob are fully customizable via CSS custom properties. All styles are gated on [data-switch-init] so the checkbox renders normally without JavaScript.
The :checked pseudo-class controls the knob position and track color. Transitions use prefers-reduced-motion to disable animation when requested.
Dynamic Elements
Switches added to the DOM after page load are automatically enhanced via a MutationObserver. No manual initialization is needed.
Accessibility
role="switch"is added automatically, announcing the control as a toggle switch to screen readers- Keyboard toggle with Space works natively since the underlying element is a real checkbox
- A visible
<label>is required — always wrap the switch in a label or usearia-label disabledandreadonlystates are conveyed to assistive technology via native attributes- Focus ring follows the system focus style via
:focus-visible prefers-reduced-motion: slide transitions are disabled when the user prefers reduced motion- Without JavaScript, the checkbox renders normally — progressive enhancement