<p class="cap-muted">Tab to the switch to see focus; Space turns it on or off.</p>
<label class="cap-switch" data-cap="switch" id="sw-focus"><input type="checkbox" role="switch" /> Show times in UTC <span class="cap-switch-state" aria-hidden="true">Off</span></label>
<p class="cap-muted">The switch has not moved yet. It is not disabled, so focus stays.</p>
<label class="cap-switch" data-cap="switch" id="sw-busy"><input type="checkbox" role="switch" aria-busy="true" /> Nightly export<span class="cap-switch-state" aria-hidden="true">Off</span></label>
Small, and invalid
<div class="cap-field-options">
<label class="cap-switch" data-cap="switch" data-size="sm" id="sw-sm"><input type="checkbox" role="switch" checked /> Dense mode <span class="cap-switch-state" aria-hidden="true">On</span></label>
<label class="cap-switch" data-cap="switch" id="sw-invalid"><input type="checkbox" role="switch" aria-invalid="true" aria-describedby="sw-invalid-why" /> Public status page <span class="cap-switch-state" aria-hidden="true">Off</span></label>
<span class="cap-field-error" id="sw-invalid-why">Verify the domain before publishing.</span>
</div>
The switch's behavior: keeps the state word beside it true. The word is "On" and "Off" unless the .cap-switch-state element sets its own in data-on and data-off.
syncWord
(label: Element): void
Writes the word for one switch's current state.
setSwitch
(label: Element, checked: boolean): void
Moves a switch from code (an Undo, a value from the server) and keeps its word true. Fires no change event, so it cannot loop back into the app's own handler.
setBusy
(label: Element, busy: boolean): void
Marks a switch pending while a request for its change runs (aria-busy, drawn as a dashed outline), and clears it when the request has answered. The switch is not disabled, so focus stays where it is.
enhance
(root?: ParentNode): () => void
Attaches to every [data-cap="switch"] under root that is not attached yet. Returns a function that detaches them all.
CSS variables
Variable
Default
--cap-sw-h
20px
--cap-sw-thumb
14px
--cap-sw-w
36px
Parts and data attributes
Class
Is
.cap-switch
the root
.cap-switch-state
a part
Attribute
Values
data-size
sm
State
Read from
:checked
the platform
:disabled
the platform
:focus-visible
the platform
:hover
the platform
[aria-busy="true"]
an attribute
[aria-invalid="true"]
an attribute
Accessibility
Key
Does
Tab
Moves to the switch
Space
Turns it on or off, at once; the word follows
A native checkbox, so it is in the tab order, labeled by its <label>, and toggled by Space and by a click anywhere on the label.
The whole label is the hit area, at least var(--target) tall.
Forced colors: the track and thumb are drawn in CanvasText, and in Highlight when on.