svelte-keydown
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")
Installation
Yarn
yarn add -D svelte-keydown
NPM
npm i -D svelte-keydown
Usage
Basic
<script>
import Keydown from "svelte-keydown";
let events = [];
</script>
<Keydown
on:Enter={() => {
events = [...events, "enter"];
}}
/>
Press "enter": {events.join(", ")}
Pause on input
Set pauseOnInput
to prevent the utility from capturing keydown events on input events.
<script>
import Keydown from "svelte-keydown";
let evt = [];
</script>
<Keydown
pauseOnInput
on:key={(e) => {
evt = [...evt, e.detail];
}}
/>
<input placeholder="Type here..." />
{evt.join("")}
Examples
Escape to Close Modal
In this use case, keydown events are paused if the modal is not open.
<script>
import Keydown from "svelte-keydown";
let showModal = true;
</script>
<Keydown paused={!showModal} on:Escape={() => (showModal = false)} />
<button on:click={() => (showModal = !showModal)}> Toggle me </button>
<br /><br />
Toggled? {showModal}
on:combo
Use the combo
dispatched event to listen for a combination of keys.
<script>
import Keydown from "svelte-keydown";
let combo = [];
</script>
<Keydown on:combo={(e) => (combo = [...combo, e.detail])} />
{combo.join(", ")}
API
Prop name | Value |
---|
paused | boolean (default: false ) |
pauseOnInput | boolean (default: false ) |
Dispatched events
on:[Key]
Example:
<Keydown on:Enter /> <Keydown on:Escape />
on:key
Alternative API to on:[Key]
.
Example:
<script>
import Keydown from "svelte-keydown";
let keys = [];
</script>
<Keydown on:key={({ detail }) => (keys = [...keys, detail])} />
<pre>
{JSON.stringify(keys, null, 2)}
</pre>
on:combo
Triggered when a sequence of keys are pressed and cleared when a keyup event is fired.
Examples:
- "Shift-S"
- "Meta-c" (Copy)
- "Meta-v" (Paste)
<script>
import Keydown from "svelte-keydown";
let combos = [];
</script>
<Keydown on:combo={({ detail }) => (combos = [...combos, detail])} />
<pre>
{JSON.stringify(combos, null, 2)}
</pre>
TypeScript
Svelte version 3.31 or greater is required to use this component with TypeScript.
TypeScript definitions are located in the types folder.
Changelog
CHANGELOG.md
License
MIT