Switch
An element which can be turned “on” or “off”.
<script lang="ts">
import { Switch } from "$lib/components/switch/index.js";
let checked = $state(false);
</script>
<label>
<input type="checkbox" bind:checked />
bind
</label>
<h2 class="text-sm">Hot Chocolate</h2>
<p class="flex">
<label class="mx-auto inline-flex items-center gap-3">
<Switch variant="outline" bind:active={checked}></Switch>
<span>Whipped Cream Option?</span>
</label>
</p>
<div class="mt-8 space-y-2">
<p class="mb-2 font-semibold">Choice: {checked ? "Whipped Cream" : "No Whipped Cream"}</p>
<p class="text-sm italic leading-tight">
{#if checked}
Whipped cream added! Extra indulgence unlocked.
{:else}
No whipped cream this time—just hot chocolate in its simplest form!
{/if}
</p>
</div>
Hot Chocolate
Choice: No Whipped Cream
No whipped cream this time—just hot chocolate in its simplest form!
Headless component
The headless component is meant to be used on a button or input element when you need a “on” - “off” semantic.
For accessibility, the label of the button should not change when the state changes. Also, all
descendants of a switch
have role presentation
. Learn more
The active
prop is bindable.
<script lang="ts">
import { choco } from "chocobytes";
import { Switch as SwitchToggle } from "chocobytes/headless/switch.svelte.js";
let active = $state(true);
const switchToggle = new SwitchToggle({
active: () => active,
setActive(v) {
active = v;
},
});
</script>
<p>
<input type="checkbox" name="bind" id="bind" bind:checked={active} />
<label for="bind" class="select-none" id="label">Bind active</label>
</p>
<div class="grid place-items-center">
<button
use:choco={switchToggle}
class="before:bg-coral relative h-6 cursor-default cursor-pointer rounded-full transition-colors before:absolute before:top-2 before:-left-4 before:h-2 before:w-2 before:rounded-full aria-checked:before:bg-green-500"
>Nutty Chocolate Option</button
>
</div>
<p class="font-semibold">{switchToggle.active ? "With nuts" : "Without nuts"}</p>
<pre>{JSON.stringify(switchToggle.attributes, null, 2)}</pre>
With nuts
{ "aria-checked": "true", "value": "", "role": "switch" }
Headless API
Prop | Default | Type | Description |
---|---|---|---|
active | false | boolean | (() => boolean) | Whether the switch is initially pressed or not. Defaults to false |
setActive | - | (v: boolean) => void | |
value | - | string |
Follows the WAI-ARIA Switch Pattern