Shortcut Listener
The ShortcutListener component listens for specific key combinations and
triggers a callback when they are pressed. This is useful for implementing
keyboard shortcuts or hotkeys in your application.
- Custom key combinations: Define any combination of keys to listen for.
- Callback triggered on match: Executes a function when the shortcut is detected.
- Supports modifier keys: Works with
Ctrl,Alt,Shift, andMeta.
Usage Example
Section titled “Usage Example”waiting...
Press Ctrl + C
or
Press Ctrl + V
<script lang="ts"> import { Kbd, ShortcutListener } from "@fefade-ui/svelte"
let message = $state("waiting...")
function handleShortcut(e: KeyboardEvent) { const keys = [] if (e.ctrlKey) { keys.push("ctrl") keys.push("+") } keys.push(e.key) message = `Shortcut ${keys.join(" ")} pressed!` }</script>
<h4>{message}</h4>
<ShortcutListener keys={["Control", "C"]} callback={handleShortcut}> <p> Press <Kbd>Ctrl</Kbd> + <Kbd>C</Kbd> </p></ShortcutListener><p>or</p><ShortcutListener keys={["Control", "V"]} callback={handleShortcut}> <p> Press <Kbd>Ctrl</Kbd> + <Kbd>V</Kbd> </p></ShortcutListener>| Prop | Type | Default | Description |
|---|---|---|---|
keys | string[] | [] | Array of keys or key names that form the shortcut combination. |
callback | (event: KeyboardEvent) => void | — | Function called when the specified keys are pressed. |
disabled | boolean | false | Whether the listener is inactive. |
once | boolean | false | If true, the callback is triggered only once per mount. |
Best Practices
Section titled “Best Practices”- Use
Kbdcomponent to display key combinations in the UI. - Avoid conflicts with native browser shortcuts.
- Combine modifier keys and regular keys to create custom shortcuts.
- Disable listeners when not needed to prevent unwanted triggers.