javascript / intermediate
Snippet
Declarative Global Event Listeners
The '<svelte:window>' special element allows you to declaratively attach event listeners to the global window object. This avoids manual 'addEventListener' calls and ensures automatic cleanup when the component is destroyed.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
<script>let lastKey = 'None';function handleKeydown(event) {lastKey = event.key;}</script><svelte:window on:keydown={handleKeydown} /><p>Focus anywhere and press a key.</p><p>Key: <strong>{lastKey}</strong></p>
svelte
Breakdown
1
<svelte:window on:keydown={handleKeydown} />
Listens for keydown events globally, regardless of where focus is.
2
lastKey = event.key;
Updates the local state reactively using the event data.