Utility to listen for keyboard events
npm install svelte-keydown[![NPM][npm]][npm-url]
> 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
``bash`
yarn add -D svelte-keydown
NPM
`bash`
npm i -D svelte-keydown
pnpm
`bash`
pnpm i -D svelte-keydown
`svelte
events = [...events, "enter"];
}}
/>
Press "enter": {events.join(", ")}
`
Set pauseOnInput to prevent the utility from capturing keydown events on input events.
`svelte
on:key={(e) => {
evt = [...evt, e.detail];
}}
/>
{evt.join("")}
`
This component forward the on:keyup and on:keydown events.
You can use on:keydown to prevent the default behavior for certain keys.
In the following example, pressing "Space" should not cause the browser page to scroll.
`svelte`
if (e.key === " ") e.preventDefault();
}}
on:Space={(e) => {
console.log("key", "Space");
}}
/>
In this use case, keydown events are paused if the modal is not open.
`svelte
`
Use the combo dispatched event to listen for a combination of keys.
`svelte
{combo.join(", ")}
`
#### separator
Use the separator property to customize the separating key between multiple keys.
`svelte
{combo.join(", ")}
`
| Prop | Type | Default value |
| :----------- | :-------- | :------------ |
| paused | boolean | false |boolean
| pauseOnInput | | false |string
| separator | | - |
- on:keyupon:keydown
-
#### on:[Key]
Example:
`svelte no-eval`
#### on:key
Alternative API to on:[Key].
Example:
`svelte
{JSON.stringify(keys, null, 2)}####
on:comboTriggered when a sequence of keys are pressed and cleared when a keyup event is fired.
Examples:
- "Shift-S"
- "Meta-c" (Copy)
- "Meta-v" (Paste)
`svelte
(combos = [...combos, detail])} />
{JSON.stringify(combos, null, 2)}
``Svelte version 3.31 or greater is required to use this component with TypeScript.
TypeScript definitions are located in the types folder.
[npm]: https://img.shields.io/npm/v/svelte-keydown.svg?color=%23ff3e00&style=for-the-badge
[npm-url]: https://npmjs.com/package/svelte-keydown