1 | # hotkey-listener
|
2 |
|
3 | A modest js library to provide low-level keyboard events the form of DOM events.
|
4 |
|
5 | ## Usage
|
6 |
|
7 | ```bash
|
8 | npm install hotkey-listener
|
9 |
|
10 | ## OR
|
11 |
|
12 | yarn add hotkey-listener
|
13 | ```
|
14 |
|
15 | ```javascript
|
16 | // index.js
|
17 |
|
18 | import hotkeyListener from "hotkey-listener"
|
19 |
|
20 | hotkeyListener.register({
|
21 | element: window,
|
22 | keys: [
|
23 | "f5",
|
24 | "ctrl+d"
|
25 | ]
|
26 | })
|
27 |
|
28 | div = document.getElementById("mydiv")
|
29 |
|
30 | div.addEventListener("keyup:f5", (event) => {
|
31 | // Prevent window refresh
|
32 | event.preventDefault()
|
33 | console.log("f5 pushed")
|
34 | })
|
35 |
|
36 | div.addEventListener("keydown:ctrl+d", (event) => {
|
37 | console.log(`event.detail.key` pushed`)
|
38 | }) // => ctrl+d pushed
|
39 | ```
|
40 |
|
41 | Hotkey listener creates custom `keyup:<keystroke>` and
|
42 | `keydown:<keystroke>` events.
|
43 |
|
44 | Events also record the key that was pressed via `event.detail.key`
|
45 |
|
46 | ## API Reference
|
47 |
|
48 | ```javascript
|
49 | hotkeyListener.register({
|
50 | element: <HTMLElement>, // Default is window
|
51 | keys: <String[]>,
|
52 |
|
53 | // https://github.com/jaywcjlove/hotkeys#option
|
54 | // element, keyup, and keydown are already predefined
|
55 | hotkeyOptions: {
|
56 | scope: <String>,
|
57 | splitKey <String>
|
58 | },
|
59 |
|
60 | // https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
|
61 | // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
|
62 | eventOptions: {
|
63 | bubbles: <Boolean>, // default false
|
64 | cancelable: <Boolean>, // default false
|
65 | composed: <Boolean>, // default false
|
66 | detail: { key: "<key pressed>" }
|
67 | },
|
68 | })
|
69 | ```
|
70 |
|
71 | ## How it works?
|
72 |
|
73 | Hotkey-Listener under the hood uses the library
|
74 | [https://github.com/jaywcjlove/hotkeys](https://github.com/jaywcjlove/hotkeys)
|
75 | to dispatch
|
76 | [CustomEvents](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).
|