Toggle
A reusable switch inspired by Fluent UI v9. It supports mouse, touch, keyboard, light/dark themes, RTL, reduced motion, and forced colors without a UI framework.
Examples
Section titled “Examples”---import Toggle from 'starlight-fluent/components/Toggle.astro';---
<Toggle label="Notifications" toggleId="notifications" name="notifications" />
<script> import { fluentToggleChange, type FluentToggleChangeEvent } from 'starlight-fluent/components/toggle';
// `event` is inferred as FluentToggleChangeEvent document.addEventListener(fluentToggleChange, (event) => { const { toggleId, checked } = event.detail; console.log(toggleId, checked); });
function onToggle(event: FluentToggleChangeEvent) { console.log(event.detail.toggleId, event.detail.checked); }</script>Types exported by starlight-fluent/components/toggle:
fluentToggleChange: the event name ("fluent-toggle-change").FluentToggleChangeDetail:{ toggleId: string; checked: boolean }.FluentToggleChangeEvent:CustomEvent<FluentToggleChangeDetail>.
Importing the module also types addEventListener on HTMLElement and Document for this event.
label and toggleId are required. Use a distinct toggleId for each setting.
labelPosition places the label "after" (default) or "before" the switch.
The wrapper exposes data-fluent-toggle and data-toggle-id, so an instance can be selected with
document.querySelector('[data-fluent-toggle][data-toggle-id="notifications"]').
class applies to the wrapper. Other attributes, including id, name, value, checked,
disabled, required, form, aria-*, and custom data-* attributes, are forwarded to the native input.
Change event
Section titled “Change event”Each user change dispatches one CustomEvent named fluent-toggle-change from the wrapper.
Its detail is { toggleId: string, checked: boolean }. It bubbles and is composed, allowing
listeners on the component or an ancestor, including document. The wrapper is the event target.
The input’s native change event is preserved. Initial rendering, form resets, and setting
input.checked programmatically do not emit change events. After a programmatic update, dispatch
input.dispatchEvent(new Event("change", { bubbles: true })) if notification is needed.
Disabled toggles cannot be changed by the user. Native form submission and reset behavior are preserved.