Debian Codegraph @

www/src/content/patterns/06-advanced/01-keyboard-shortcuts.md

raw symbols SCIP
1 ---
2 includeMockServer: true
3 title: "Keyboard Shortcuts"
4 description: Bind keyboard shortcuts to interactive elements
5 icon: "icon-[mdi--keyboard]"
6 soon: true
7 ---
8
9 <script>
10 server.get("/init", () => `
11 <div class="flex items-center gap-4">
12 <button class="px-4 py-2 text-sm font-medium rounded-md cursor-pointer text-neutral-600 dark:text-neutral-300 border border-neutral-200 dark:border-neutral-700 hover:bg-neutral-50 dark:hover:bg-neutral-850 hover:text-neutral-800 dark:hover:text-neutral-100 active:scale-[0.98] transition"
13 hx-trigger="click, keyup[altKey&&shiftKey&&key=='D'] from:body"
14 hx-post="/doit"
15 hx-target="#result">
16 Do It! (Alt+Shift+D)
17 </button>
18 <span id="result"></span>
19 </div>`);
20
21 server.post("/doit", () =>
22 `<span class="inline-block px-3 py-1.5 rounded-md text-sm font-semibold bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200 starting:opacity-0 transition-opacity duration-300">Done!</span>`
23 );
24
25 server.start("/init");
26 </script>
27
28 <div id="demo-content" class="not-prose demo-container flex justify-center"></div>
29
30 ## Basic usage
31
32 On the client, add a keyboard event to `hx-trigger` alongside `click`.
33
34 ```html
35 <button hx-trigger="click, keyup[altKey&&shiftKey&&key=='D'] from:body"
36 hx-post="/doit">
37 Do It! (Alt+Shift+D)
38 </button>
39 ```
40
41 - [`hx-trigger`](/reference/attributes/hx-trigger) accepts multiple events separated by commas.
42 - `keyup[altKey&&shiftKey&&key=='D']` uses an [event filter](/reference/attributes/hx-trigger#event-filters) to match only the Alt+Shift+D combination.
43 - [`from:body`](/reference/attributes/hx-trigger#from) makes the shortcut global: the listener is on the `<body>`, not the button itself.
44
45 On the server, respond with the result content:
46
47 ```html
48 <span>Done!</span>
49 ```
50
51 ## Notes
52
53 ### Keyboard event properties
54
55 The filter expression inside `[...]` has access to the raw [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) properties: `key`, `code`, `altKey`, `ctrlKey`, `shiftKey`, and `metaKey`. Combine them with `&&` and `||` to match any shortcut.
56
57 For details on key values, see [Keyboard Events on javascript.info](https://javascript.info/keyboard-events).