Hooks

useEscapeKeydown

A Svelte action that detects Escape key presses on an element. Useful for closing dialogs, modals, dropdowns, and any dismissible UI.

Basic Usage

Focus on the box below and press Escape to trigger the handler. Usage: use:useEscapeKeydown={{ handler }}

Focus here and press Escape
Press Escape to trigger the handler
<script lang="ts">
  import { Badge } from 'sv5ui';
  import { useEscapeKeydown, toast } from 'sv5ui';

  let escapeCount = $state(0);

  function handleEscape() {
    escapeCount += 1;
    toast('Escape key pressed!');
  }
</script>

<!-- Svelte action: focus the element, then press Escape -->
<div use:useEscapeKeydown={{ handler: handleEscape }} tabindex="0"
  class="rounded-lg border-2 border-dashed border-primary/40 bg-primary/10 p-6 text-center">
  <p>Focus here and press Escape</p>
  <Badge label={String(escapeCount)} variant="soft" color="primary" size="xs" />
</div>

Enable / Disable

Toggle the enabled option to control whether Escape key presses are detected.

Detection active - focus and press Escape
Press Escape to trigger the handler
<script lang="ts">
  import { Switch, FormField } from 'sv5ui';
  import { useEscapeKeydown, toast } from 'sv5ui';

  let enabled = $state(true);

  function handleEscape() {
    toast('Escape detected!');
  }
</script>

<FormField label="Enabled" size="sm">
  <Switch bind:checked={enabled} size="sm" />
</FormField>

<div use:useEscapeKeydown={{ handler: handleEscape, enabled }} tabindex="0"
  class="rounded-lg border-2 border-dashed p-6 text-center">
  Detection is {enabled ? 'ON' : 'OFF'}
</div>

Options

Passed as an object to the Svelte action.

OptionTypeDefault
handler(event: KeyboardEvent) => void-
enabledbooleantrue