Part 3 / Special elements / <svelte:window>
Just as you can add event listeners to any DOM element, you can add event listeners to the window
object with <svelte:window>
.
On line 11, add the keydown
listener:
App.svelte
<svelte:window on:keydown={handleKeydown}/>
As with DOM elements, you can add event modifiers like
preventDefault
.
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
44
<script>
let key;
let keyCode;
function handleKeydown(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 {
background-color: #eee;
border-radius: 4px;
font-size: 6em;
padding: 0.2em 0.5em;
border-top: 5px solid rgba(255, 255, 255, 0.5);
border-left: 5px solid
rgba(255, 255, 255, 0.5);
border-right: 5px solid rgba(0, 0, 0, 0.2);
border-bottom: 5px solid rgba(0, 0, 0, 0.2);
color: #555;
}
</style>
initialising