Button·Free
Toggle switch (Svelte)
An on/off switch for Svelte 5. It is a button with role switch, so Space, Enter and screen readers work. You can bind checked or pass onchange, add a second line of text or disable it. The colours come from CSS variables.
Free to install.
If PocketCode is installed on your Android device, this opens the page in the app.
Preview
ToggleSwitch.svelte · 138 lines
<!--
An on/off switch for Svelte 5 (runes + TypeScript). It is a real <button role="switch">:
Space and Enter toggle it, and screen readers say its name and whether it is on.
Bind the value, or listen to `onchange`:
<ToggleSwitch label="Dark mode" bind:checked={dark} />
<ToggleSwitch label="Sync over mobile data" checked={sync} onchange={(on) => save(on)} />
Colours: --switch-on (the track when on), --switch-off, --switch-thumb, --switch-text.
-->
<script lang="ts">
interface Props {
label: string;
checked?: boolean;
disabled?: boolean;
/** A second line under the label. */
description?: string;
onchange?: (checked: boolean) => void;
}
let { label, checked = $bindable(false), disabled = false, description, onchange }: Props = $props();
const uid = $props.id();
function toggle() {
if (disabled) return;
checked = !checked;
onchange?.(checked);
}
</script>
<div class="row">
<span class="text">
<span id="{uid}-label" class="label">{label}</span>
{#if description}
<span id="{uid}-description" class="description">{description}</span>
{/if}
</span>
<button
type="button"
role="switch"
aria-checked={checked}
aria-labelledby="{uid}-label"
aria-describedby={description ? `${uid}-description` : undefined}
{disabled}
onclick={toggle}
>
<span class="thumb" aria-hidden="true"></span>
</button>
</div>
<style>
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
min-height: 48px;
font-family: system-ui, sans-serif;
color: var(--switch-text, #1d1f23);
}
.text {
display: grid;
gap: 0.15rem;
}
.label {
font-weight: 500;
}
.description {
font-size: 0.875rem;
opacity: 0.75;
}
button {
position: relative;
flex: none;
box-sizing: border-box;This preview is shortened. You get the full content when you install it.
Changes in 1.0.0
First version.