Skip to main content

Toggle

A two-state button that can be either on or off.

Features

  • Full keyboard navigation
  • Can be controlled or uncontrolled

Anatomy

  • Toggle: The toggle component

Usage

To create a toggle, use the createToggle builder function. Follow the anatomy or the example above to create your toggle.

Disabling the toggle

To disable a the toggle, set the disabled argument to true.

    <script lang="ts">
  import { createToggle } from '@melt-ui/svelte'
 
  const {
    options: { disabled }
  } = createToggle({
    disabled: true
  })
  // or
  disabled.set(true)
  // or
  disabled.update((d) => !d)
</script>
	
    <script lang="ts">
  import { createToggle } from '@melt-ui/svelte'
 
  const {
    options: { disabled }
  } = createToggle({
    disabled: true
  })
  // or
  disabled.set(true)
  // or
  disabled.update((d) => !d)
</script>
	

API Reference

createToggle

The builder function used to create the toggle component.

Props

Prop Default Type / Description
disabled false
boolean

Whether or not the toggle is disabled.

defaultPressed false
boolean

Whether or not the toggle is pressed.

pressed -
Writable<boolean>

A writable store that controls the pressed state of the toggle.

See Bring Your Own Store

onPressedChange -
ChangeFn<boolean>

A callback called when the value of the pressed store should be changed. This is useful for controlling the value of the toggle from outside the toggle.

See Change Functions

Elements

Element Description

The builder store used to create the toggle root.

States

State Description
pressed

A writable store that represents the pressed state of the toggle.

Options

Option Description
disabled

Whether or not the toggle is disabled.

root

The root toggle component.

Data Attributes

Data Attribute Value
[data-disabled]

Present when the toggle is disabled.

[data-state]

'on' | 'off'

[data-melt-toggle]

Present on all toggle elements.

Custom Events

Event Value
m-click (e: ) => void
m-keydown (e: ) => void

Accessibility

Adheres to the Button WAI-ARIA design pattern

Key Behavior
Space

Activates/deactivates the toggle.

Enter

Activates/deactivates the toggle.