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:

  1. Sets appearance: none on the checkbox to remove native styling
  2. Renders a track and sliding knob via CSS pseudo-elements
  3. Adds role="switch" to the element for proper semantics
  4. Responds to the checked state with a slide transition
  5. Sets data-switch-init to 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.

You must agree before continuing.

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.

Notification preferences

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.