Toggle

A button which can be in either of two states, like “on” and “off”, “pressed” and “not pressed”.

Are you craving chocolate?

Not Craving. Maybe later!


Headless component

The headless component is meant to be used on a button element when you need a “pressed” - “not pressed” semantic.

For accessibility, the label of the button should not change when the state changes.

The active prop is bindable.


<script lang="ts">
  import { choco } from "chocobytes";
  import { ToggleButton } from "chocobytes/headless/toggle.svelte.js";

  let active = $state(true);

  const toggle = new ToggleButton({ active: () => active, setActive: (v) => (active = v) });
</script>

<label>
  <span>bind</span>
  <input type="checkbox" bind:checked={active} />
</label>

<p class="text-center">Indulge in Chocolate?</p>
<p class="flex justify-center">
  <button
    class="py-2 px-4 outline aria-pressed:bg-white aria-pressed:text-orange-950"
    use:choco={toggle}>Indulge</button
  >
</p>

<p>
  {#if active}
    Indulgent mode activated! Go all out with a rich chocolate cake, double chocolate cookies, or
    that extra-large chocolate bar.
  {:else}
    Keeping it minimal for now. Maybe just a tiny square of dark chocolate or a light chocolate
    snack
  {/if}
</p>

<pre>{JSON.stringify(toggle.attributes, null, 2)}</pre>

API

PropDefaultTypeDescription
activefalseboolean | (() => boolean)Whether the toggle is initially pressed or not. Defaults to false
setActive-(v: boolean) => void
value-string

Follows the WAI-ARIA Toggle Button Pattern