Skip to main content

Just as you can add event listeners to any DOM element, you can add event listeners to the window object with <svelte:window>.

We’ve already got an onkeydown function declared — now all we need to do is wire it up:

App
<svelte:window {onkeydown} />

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<script>
	let key = $state();
	let keyCode = $state();
 
	function onkeydown(event) {
		key = event.key;
		keyCode = event.keyCode;
	}
</script>
 
<svelte:window />
 
<div style="text-align: center">
	{#if key}
		<kbd>{key === ' ' ? 'Space' : key}</kbd>
		<p>{keyCode}</p>
	{:else}
		<p>Focus this window and press any key</p>
	{/if}
</div>
 
<style>
	div {
		display: flex;
		height: 100%;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}
 
	kbd {
		border-radius: 4px;
		font-size: 6em;
		padding: 0.2em 0.5em;
		background-color: #eeeeee;
		border-top: 5px solid #f9f9f9;
		border-left: 5px solid #f9f9f9;
		border-right: 5px solid #aaaaaa;
		border-bottom: 5px solid #aaaaaa;
		color: #555;
	}
</style>