Switch
Introduction
Section titled “Introduction”An on/off setting that takes effect immediately. Switch renders a native <input type="checkbox" role="switch"> restyled as a track, with a decorative thumb whose position shows the state. Switches have no required state: a switch is a setting, not a question. Validity is always valid unless a custom error is set, for example when saving the setting failed.
- Immediate settingsAn on/off control for settings that take effect right away.
- Native underneathA native checkbox with the switch role keeps keyboard and form behavior.
- Save failuresShow a custom error when saving the setting fails.
- Form readySubmits its value with the form like a checkbox.
Use it for
- A binary setting that applies immediately, such as enabling notifications or dark mode.
- Settings pages where each row toggles one feature.
Use something else for
- A choice that is only applied when a form is submitted: use Checkbox.
- A choice the user must confirm (“I agree”): use a required Checkbox.
- More than two states: use Radio Group or Select.
Anatomy
<div class="aui-field aui-switch" data-aui-control> (consumer host) <div class="aui-switch__row"> <span class="aui-switch__control"> <input type="checkbox" role="switch" class="aui-switch__input"> <span class="aui-switch__thumb" aria-hidden="true"> </span> <label class="aui-field__label aui-switch__label" for=input>Label</label> </div> <div class="aui-field__description"> (optional) <div class="aui-field__error aui-validation-message"> (custom error, when shown)</div>Live example
Section titled “Live example”Use the bar above each frame to switch theme, density, direction, and locale.
Switch in the Employee profile form showcase
Section titled “Switch in the Employee profile form showcase”The part of the Employee profile form showcase that uses Switch. Change its options, use it with the keyboard, and watch the event log; the link in the frame opens the full showcase. The bar above the frame switches theme, density, direction, and locale.
Showcase source
// Forms showcase: an employee profile form that uses every form control together,// with constraint validation, a cross-field rule, the error summary, reset, and live options.import { Button } from '@absoluteui/components/button';import { Checkbox } from '@absoluteui/components/checkbox';import { CheckboxGroup } from '@absoluteui/components/checkbox-group';import { Combobox } from '@absoluteui/components/combobox';import { Fieldset } from '@absoluteui/components/fieldset';import { Form, type FormSubmitDetail } from '@absoluteui/components/form';import { FormField } from '@absoluteui/components/form-field';import { MultiSelect } from '@absoluteui/components/multi-select';import { NumberInput } from '@absoluteui/components/number-input';import { RadioGroup } from '@absoluteui/components/radio-group';import { Select } from '@absoluteui/components/select';import { Slider } from '@absoluteui/components/slider';import { Switch } from '@absoluteui/components/switch';import { TextInput } from '@absoluteui/components/text-input';import { Textarea } from '@absoluteui/components/textarea';import { ValidationMessage } from '@absoluteui/components/validation-message';import { action, annotate, choice, createShowcase, hostIn, toggle } from './kit.js';
const sc = createShowcase({ title: 'Employee profile', description: 'Every form control in one form: required fields, formats, ranges, a cross-field rule, and an error summary on submit.',});
const form = document.createElement('form');form.className = 'sc-form';form.noValidate = true;sc.stage.append(form);
// Each fieldset declares its controls, so a component's focus view shows its own group.const fieldset = (legend: string, description?: string): HTMLFieldSetElement => { const fs = document.createElement('fieldset'); form.append(fs); Fieldset.enhance(fs, { legend, ...(description ? { description } : {}) }); return fs;};
const DEPARTMENTS = [ { value: 'eng', label: 'Engineering' }, { value: 'fin', label: 'Finance' }, { value: 'hr', label: 'People' }, { value: 'ops', label: 'Operations' }, { value: 'sales', label: 'Sales' },];const MANAGERS = ['Ada Kowalski', 'Bruno Silva', 'Chen Wei', 'Divya Nair', 'Emeka Obi', 'Farah Haddad', 'Grace Liu', 'Hiro Tanaka'].map((name) => ({ value: name.toLowerCase().replace(/\s+/g, '-'), label: name }));const SKILLS = ['Accessibility', 'Angular', 'Data analysis', 'Design systems', 'Finance', 'Negotiation', 'People management', 'TypeScript'].map((s) => ({ value: s.toLowerCase().replace(/\s+/g, '-'), label: s }));
// Personal details.const personal = annotate(fieldset('Personal details'), ['form', 'error-summary', 'fieldset', 'text-input', 'textarea', 'form-field']);const name = TextInput.create(hostIn(personal), { label: 'Full name', name: 'name', required: true, minLength: 2, autocomplete: 'name' });const email = TextInput.create(hostIn(personal), { label: 'Work email', name: 'email', type: 'email', required: true, autocomplete: 'email', description: 'Used for sign-in and notifications.' });const phone = TextInput.create(hostIn(personal), { label: 'Phone', name: 'phone', type: 'tel', inputMode: 'tel', pattern: '[+]?[0-9 ]{7,20}', description: 'Digits and spaces, with an optional leading +.' });const bio = Textarea.create(hostIn(personal), { label: 'About', name: 'bio', maxLength: 280, showCounter: true, rows: 3, resize: 'vertical' });
// A native control labelled and validated by Form Field.const badge = document.createElement('input');badge.name = 'badge';badge.inputMode = 'numeric';badge.pattern = '[0-9]{6}';FormField.create(hostIn(personal), { label: 'Badge number', control: badge, description: 'Six digits printed on your badge.' });
// Role.const role = annotate(fieldset('Role'), ['form', 'error-summary', 'validation-message', 'fieldset', 'select', 'combobox', 'radio-group', 'number-input', 'slider', 'multi-select']);const department = Select.create(hostIn(role), { label: 'Department', name: 'department', options: DEPARTMENTS, placeholder: 'Choose a department', required: true });const manager = Combobox.create(hostIn(role), { label: 'Manager', name: 'manager', options: MANAGERS, placeholder: 'Type a name', description: 'Search by first or last name.' });const type = RadioGroup.create(hostIn(role), { label: 'Employment type', name: 'type', orientation: 'horizontal', required: true, options: [{ value: 'full', label: 'Full time' }, { value: 'part', label: 'Part time' }, { value: 'contract', label: 'Contractor' }] });const salary = NumberInput.create(hostIn(role), { label: 'Annual salary', name: 'salary', min: 10000, max: 500000, step: 1000, format: { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 } });const hours = Slider.create(hostIn(role), { label: 'Weekly hours', name: 'hours', min: 8, max: 48, step: 1, largeStep: 4, value: 40, marks: [{ value: 20, label: '20' }, { value: 40, label: '40' }], showValue: true });const skills = MultiSelect.create(hostIn(role), { label: 'Skills', name: 'skills', options: SKILLS, maxSelected: 5, description: 'Up to five.' });
// Preferences.const prefs = annotate(fieldset('Preferences', 'You can change these later in settings.'), ['form', 'error-summary', 'fieldset', 'checkbox-group', 'switch', 'checkbox']);const benefits = CheckboxGroup.create(hostIn(prefs), { label: 'Benefits', name: 'benefits', orientation: 'horizontal', options: [{ value: 'health', label: 'Health' }, { value: 'pension', label: 'Pension' }, { value: 'transit', label: 'Transit pass' }, { value: 'gym', label: 'Gym' }] });const remote = Switch.create(hostIn(prefs), { label: 'Works remotely', name: 'remote' });const terms = Checkbox.create(hostIn(prefs), { label: 'I confirm these details are correct', name: 'terms', required: true });
// A standalone validation message for a rule that is not tied to one control.const actions = annotate(hostIn(form), ['form', 'error-summary', 'validation-message']);actions.className = 'sc-form__actions';const hint = ValidationMessage.create(hostIn(actions), { tone: 'info', message: 'Part-time employees work at most 32 hours per week.' });
const buttons = hostIn(actions);buttons.className = 'sc-form__buttons';const submit = Button.create({ text: 'Save profile', variant: 'primary', type: 'submit' }, document);const reset = Button.create({ text: 'Reset', variant: 'secondary', type: 'reset' }, document);buttons.append(submit.element, reset.element);
const formController = Form.create(form, { summaryTitle: 'Fix these fields to save the profile', rules: [ { fields: ['type', 'hours'], validate: (values) => (values.type === 'part' && Number(values.hours) > 32 ? 'Part-time employees work at most 32 hours per week.' : null), }, ],});
form.addEventListener('aui-submit', (e) => { const { values } = (e as CustomEvent<FormSubmitDetail>).detail; submit.setLoading(true); // A save takes a moment; the button stays busy and focusable meanwhile. setTimeout(() => { submit.setLoading(false); hint.update({ tone: 'success', message: `Saved the profile of ${typeof values.name === 'string' ? values.name : 'the employee'}.` }); }, 600);});form.addEventListener('aui-reset', () => { hint.update({ tone: 'info', message: 'Part-time employees work at most 32 hours per week.' });});
sc.listen(form, ['aui-submit', 'aui-invalid', 'aui-reset'], 'form');for (const [label, host] of [ ['name', name.host], ['email', email.host], ['department', department.host], ['manager', manager.host], ['type', type.host], ['salary', salary.host], ['hours', hours.host], ['skills', skills.host], ['benefits', benefits.host], ['remote', remote.host], ['terms', terms.host],] as const) { sc.listen(host, ['aui-change'], label);}
// Options.const all = [name, email, phone, bio, department, manager, type, salary, hours, skills, benefits, remote, terms];toggle(sc, 'Disabled', false, (disabled) => { for (const c of all) c.update({ disabled }); badge.disabled = disabled; submit.update({ disabled });});toggle(sc, 'Read-only', false, (readOnly) => { for (const c of [name, email, phone, bio, department, manager, salary, skills]) c.update({ readOnly }); badge.readOnly = readOnly;});choice( sc, 'Validate', [ { value: 'blur', label: 'When leaving a field' }, { value: 'input', label: 'While typing' }, { value: 'submit', label: 'On submit only' }, ], 'blur', (timing) => { for (const c of [name, email, phone, bio, department, type, salary, benefits, terms]) c.update({ validationTiming: timing }); },);action(sc, 'Fill sample data', () => { name.setValue('Ada Lovelace'); email.setValue('ada@example.com'); phone.setValue('+44 20 7946 0000'); bio.setValue('Writes the first programs and reviews every pull request.'); badge.value = '204816'; department.setValue('eng'); manager.setValue('chen-wei'); type.setValue('full'); salary.setValue(86000); hours.setValue(38); skills.setValue(['typescript', 'accessibility']); benefits.setValue(['health', 'pension']); remote.setChecked(true); terms.setChecked(true); sc.log('sample data filled');});action(sc, 'Submit empty', () => { formController.reset(); formController.submit();}, ['form', 'error-summary']);Setting that applies immediately
Section titled “Setting that applies immediately”import { Switch } from '@absoluteui/components/switch';
const host = document.createElement('div');document.body.append(host);const notifications = Switch.create(host, { label: 'Email notifications', description: 'Weekly summary of activity' });host.addEventListener('aui-change', () => { document.documentElement.dataset.notifications = String(notifications.checked);});Reporting a failed save
Section titled “Reporting a failed save”import { Switch } from '@absoluteui/components/switch';
const host = document.createElement('div');document.body.append(host);const sync = Switch.create(host, { label: 'Sync across devices', checked: true });
async function save(on: boolean): Promise<void> { const response = await fetch('/api/settings/sync', { method: 'PUT', body: JSON.stringify({ on }) }); if (!response.ok) { sync.setChecked(!on); sync.setCustomError('Could not save. Try again.'); sync.reportValidity(); }}
host.addEventListener('aui-change', () => { void save(sync.checked);});Install and start
Section titled “Install and start”npm install @absoluteui/components @absoluteui/core @absoluteui/themeRegistry setup, the theme stylesheet, and the Content Security Policy are covered in Installation.
import { Switch } from '@absoluteui/components/switch';import '@absoluteui/components/switch/style.css';First use
Section titled “First use”import { Switch } from '@absoluteui/components/switch';import '@absoluteui/components/switch/style.css';
const host = document.querySelector<HTMLElement>('#dark-mode');if (host) { const dark = Switch.create(host, { label: 'Dark mode' }); host.addEventListener('aui-change', () => { document.documentElement.dataset.auiTheme = dark.checked ? 'absolute-dark' : 'absolute-default'; });}More usage
import { Switch } from '@absoluteui/components/switch';
const host = document.createElement('div');document.body.append(host);Switch.create(host, { label: 'Email notifications', description: 'Weekly summary of activity' });Using Angular? See Switch for Angular.
API reference
Section titled “API reference”Factory
Section titled “Factory”Switch.create(host: HTMLElement, options: SwitchOptions): SwitchGlobal configuration key: switch (see Configuration).
Options
Section titled “Options”| Option | Type | Default | Description |
|---|---|---|---|
label |
string |
Visible label and accessible name; clicking it toggles the switch. Required. | |
hideLabel |
boolean |
false |
Visually hide the label; it remains the accessible name. |
checked |
boolean |
false |
Initial on/off state; also restored by reset(). |
value |
string |
"on" |
Submitted value when on. |
name |
string |
Form field name. | |
description |
string |
Help text referenced by aria-describedby. | |
disabled |
boolean |
false |
Disables the switch. |
icons |
Partial<{ error: IconRef }> |
Icon slot overrides. | |
validationTiming |
'blur' | 'input' | 'submit' |
"blur" |
When a custom error message first appears; afterwards it updates live. Globally configurable. |
locale |
string |
"en-US" |
Message locale. Globally configurable. Inherited from common configuration. |
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
host |
HTMLElement |
Consumer host; its children are owned by the component. |
input |
HTMLInputElement |
The native checkbox with role=switch. |
checked |
boolean |
Current on/off state. |
value |
string |
Submitted value when on. |
name |
string | null |
Form field name. |
label |
string |
Label text. |
disabled |
boolean |
Disabled state. |
validity |
FieldValidity |
Always valid unless a custom error is set. |
dirty |
boolean |
State differs from the initial state. |
touched |
boolean |
Focus has left the control at least once. |
options |
Readonly<SwitchOptions> |
Current instance options. |
Methods
Section titled “Methods”| Method | Description |
|---|---|
setChecked(checked: boolean): void |
Programmatic state (no events); clears an external custom error. |
update(options: Partial<SwitchOptions>): void |
Merge and apply options. |
reportValidity(): boolean |
Show a custom error now and return validity. |
setCustomError(message: string | null): void |
External error, for example a failed save; cleared when the user toggles. |
getFormValue(): string | null |
value when on, otherwise null. |
focus(): void |
Focus the switch. |
reset(): void |
Restore the initial state and clear dirty/touched/submitted state. |
destroy(): void |
Remove rendering, listeners, registration, and subscriptions. |
Events
Section titled “Events”| Event | Detail | Bubbles | Cancelable | Description |
|---|---|---|---|---|
aui-change |
{ checked: boolean; value: string } |
Yes | No | The user toggled the switch. |
CSS classes
Section titled “CSS classes”All rules live in the aui.components cascade layer, so application styles override them without specificity battles.
| Class | Purpose |
|---|---|
aui-field aui-switch |
Host. |
aui-switch--invalid | --disabled |
State modifiers on the host. |
aui-field__label | __description | __error |
Shared field chrome. |
aui-switch__row |
Track and label row. |
aui-switch__control |
Positioning wrapper for the track and thumb. |
aui-switch__input |
Native input, restyled as the track. |
aui-switch__thumb |
Decorative thumb; its position shows the state. |
aui-switch__label |
The label (also aui-field__label). |
Icon slots
Section titled “Icon slots”| Slot | Default icon |
|---|---|
error |
alert-circle |
Design tokens
Section titled “Design tokens”Tokens this stylesheet reads (verified in CI). Override them in a theme or with the Theme Designer.
--aui-border-width | --aui-color-border | --aui-color-border-strong | --aui-color-disabled-bg | --aui-color-error-fg | --aui-color-focus-ring | --aui-color-on-primary | --aui-color-primary | --aui-color-surface | --aui-color-surface-sunken | --aui-color-text | --aui-color-text-disabled | --aui-color-text-muted | --aui-duration-fast | --aui-easing-standard | --aui-focus-ring-offset | --aui-focus-ring-width | --aui-font-family-sans | --aui-font-size-md | --aui-font-size-sm | --aui-font-weight-medium | --aui-font-weight-regular | --aui-icon-size-sm | --aui-line-height-normal | --aui-line-height-tight | --aui-radius-pill | --aui-space-1 | --aui-space-2 | --aui-switch-height | --aui-switch-width | --aui-touch-target-min
TypeScript definitions
type ValidationTiming = 'blur' | 'input' | 'submit';interface SwitchIcons { error: IconRef }interface SwitchChangeDetail { checked: boolean; value: string }Accessibility and performance
Section titled “Accessibility and performance”Accessibility
Section titled “Accessibility”Pattern: Native <input type=“checkbox” role=“switch”> with a <label for> association (WAI-ARIA APG Switch).
Checked on every docs build: the showcase passes axe (WCAG 2.2 A and AA rules) in the default, dark, and high-contrast themes and right to left; the playground loads without errors and passes axe before and after every on/off option is switched, with no Content Security Policy violations.
Keyboard
Section titled “Keyboard”| Key | Context | Action |
|---|---|---|
| Tab / Shift+Tab | Any | Moves focus to and from the switch. |
| Space | Switch focused | Toggles on/off (native). |
| Element | Role |
|---|---|
| input | switch (explicit on a native checkbox; checked state maps to on/off) |
| thumb and icons | none (aria-hidden=true) |
ARIA attributes
Section titled “ARIA attributes”| Attribute | Element | Value |
|---|---|---|
role |
input | “switch” |
aria-describedby |
input | Help text and visible error message ids |
aria-invalid |
input | “true” only while a custom error message is shown |
The native input (the track) is the focus target and shows a color-focus-ring outline on :focus-visible.
WCAG 2.2 success criteria addressed
Section titled “WCAG 2.2 success criteria addressed”Automated test results: Accessibility and compliance.
Notes and known caveats
Section titled “Notes and known caveats”- The state is shown by the thumb position as well as by color.
- Clicking the label toggles the switch, extending the hit target.
- Enter does not toggle (native checkbox behavior); Space does.
- Switches have no required state; a failed save can be reported with setCustomError.
- Screen-reader announcement of role=switch on/off has not yet been manually verified with NVDA, JAWS, and VoiceOver.
Performance
Section titled “Performance”| Import cost | Minified | gzip | brotli | CSS brotli |
|---|---|---|---|---|
@absoluteui/components/switch |
38.5 kB | 13.1 kB | 11.7 kB | 1.0 kB |
Measured at build time, including every AbsoluteUI module the component pulls in. No third-party runtime dependencies.
| Budget (enforced in CI) | Limit |
|---|---|
| Switch.create, per instance (1,000 instances) | < 1 ms average in headless Chromium (target; not yet covered by the performance test) |
Tested scale: Unit-tested per instance; not yet included in the 1,000-instance performance test.
Two listeners per instance (change, focusout), a shared document-level pointer tracker, and one configuration subscription. Target: under 1 ms per Switch.create; not yet covered by the performance test.
Measured run times: Performance.
Details
Section titled “Details”States
off, on, hover, focus-visible, disabled, disabled on, invalid (custom error shown).
State transitions
| From | Trigger | To |
|---|---|---|
| off | click, label click, or Space | on; aui-change |
| on | click, label click, or Space | off; aui-change |
| any | focus leaves the host | touched; a custom error is shown (blur timing) |
| invalid (custom error) | user toggles | custom error cleared |
| any | reset() |
initial state; pristine, untouched |
Accessibility notes
- The state is shown by thumb position as well as color (WCAG 1.4.1).
- The label is clickable, so the target is the whole row (WCAG 2.5.8).
- The label should describe the setting and stay constant; do not change it to “On”/“Off”.
- Reduced motion removes the thumb transition.
- Manual screen-reader verification is pending (see Known limitations).
Responsive behavior
The track is fixed-size (switch-width by switch-height); the label wraps beside it. Help text and messages align with the label.
Right-to-left
The thumb uses inset-inline-start, so “on” moves it to the inline end in both directions (right in LTR, left in RTL) without direction-specific rules.
Theming
Off: color-surface-sunken track with a color-border-strong boundary and thumb. On: color-primary track with a color-on-primary thumb. High-contrast themes widen border-width. In forced-colors mode the track uses Canvas/CanvasText when off and Highlight/HighlightText when on, and disabled uses GrayText, with forced-color-adjust: none.
Global configuration
configureAbsoluteUI({ components: { switch: { validationTiming: 'submit' } } });Changes apply to existing instances immediately. validationTiming only affects when a custom error first appears.
Component configuration
Instance options override global and theme defaults. All options are dynamic.
Icons
icons.error (default alert-circle). The thumb is a CSS shape, not an icon.
Security
All text uses textContent. CSP-safe: no inline styles or HTML strings.
Data handling
No persistence, network access, or telemetry. With name, the native input submits name=value when on.
Supported data scale
One value per instance. Not yet included in the 1,000-instance performance test.
Edge cases
reportValidity()returnstrueunless a custom error is set.setChecked()clears a custom error, so revert the state first and then set the error when a save fails.- A disabled switch is not submitted natively, but
getFormValue()still reports its value.
Errors
| Code | Category | Cause |
|---|---|---|
SWITCH_OPTIONS |
configuration | Missing label or non-string value. |
Validation (validity.error) |
validation | custom only (set through setCustomError). |
A failed construction leaves no rendering, listeners, or subscriptions behind.
Known limitations
- No
requiredorvalidateoption by design; use a Checkbox for choices that must be confirmed. - No on/off text inside the track.
- The track alone is 2.25rem by 1.25rem; the 24px target is met by the row and label.
- Screen-reader behavior of
role="switch"has not yet been manually verified with NVDA, JAWS, and VoiceOver.
Unsupported scenarios
- A mixed/indeterminate state.
- HTML inside the label.
(c) 2026 Kasadara Technology Solutions Pvt Ltd. AbsoluteUI is free to use under the AbsoluteUI Free Use License; it is not open source.