Utility to listen for keyboard events.
Utility component leveraging the svelte:body API to listen for keydown events.
Use Cases
- toggle modals
- capture a combination of keys (i.e., "Meta-s")
yarn add -D svelte-keydown
# OR
npm i -D svelte-keydown
<script>
import Keydown from "svelte-keydown";
let events = [];
</script>
<Keydown on:Enter="{() => { events = [...events, 'enter'] }}" />
Press "enter": {events.join(', ')}
In this use case, keydown events are paused if the modal is not open.
<script>
let showModal = true;
function closeModal() {
showModal = false;
}
</script>
<Keydown paused="{!showModal}" on:Escape="{closeModal}" />
<button on:click="{() => { showModal = !showModal; }}">Toggle modal</button>
<br />
Toggled {showModal}
Use the combo
dispatched event to listen for a combination of keys.
<script>
let save = [];
</script>
<Keydown
on:combo="{(e) => {
if (e.detail === 'Meta-s') {
console.log('Save');
save = [...save, e.detail]
}
}}"
/>
{save.join(', ')}
Prop name | Value |
---|---|
paused | boolean (default: false ) |
Example:
<Keydown on:Enter />
<Keydown on:Escape />
Alternative API to on:[Key]
.
Example:
<Keydown
on:key={({ detail }) => {
console.log(detail); // string | "Enter"
}} />
Triggered when a sequence of keys are pressed and cleared when a keyup event is fired.
Example:
<Keydown
on:combo={({ detail }) => {
console.log(detail); // "Meta-Shift-a"
}} />
Svelte version 3.31 or greater is required to use this module with TypeScript.