Action

Escape Key

Detects and handles the Escape key press.

/// DEMO ///

Press escape key

///

1
<script>
2
  import { escapeKey } from '$lib/actions/escape-key.svelte';
3
</script>
4

5
<div use:escapeKey={() => alert('^_^')}>
6
  <p>Press escape key</p>
7
</div>
8

Guide

Create the action.

1
// Track components using escape key action
2
const activeKeyListeners: Set<HTMLElement> = new Set();
3

4
export function escapeKey(node: HTMLElement, callback: (event: KeyboardEvent) => void) {
5
  function handleKeydown(event: KeyboardEvent) {
6
    if (event.key === 'Escape') {
7
      // Execute the callback of top most element
8
      const elements = Array.from(activeKeyListeners);
9
      const topmostElement = elements[elements.length - 1];
10
      if (node === topmostElement) callback(event);
11
    }
12
  }
13

14
  $effect(() => {
15
    activeKeyListeners.add(node);
16
    document.addEventListener('keydown', handleKeydown);
17

18
    return () => {
19
      activeKeyListeners.delete(node);
20
      document.removeEventListener('keydown', handleKeydown);
21
    };
22
  });
23
}
24

Share treats:

Copyright © 2025 - Cliemtor Fabros