UNPKG

12 kBMarkdownView Raw
1# Hotkeys
2
3<!--dividing-->
4
5[![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-048754?logo=buymeacoffee)](https://jaywcjlove.github.io/#/sponsor)
6[![](https://img.shields.io/npm/dm/hotkeys-js?logo=npm)](https://www.npmjs.com/package/hotkeys-js)
7[![](https://img.shields.io/github/stars/jaywcjlove/hotkeys-js.svg)](https://github.com/jaywcjlove/hotkeys/stargazers)
8![no dependencies](http://jaywcjlove.github.io/sb/status/no-dependencies.svg)
9[![GitHub Actions CI](https://github.com/jaywcjlove/hotkeys-js/actions/workflows/ci.yml/badge.svg)](https://github.com/jaywcjlove/hotkeys-js/actions/workflows/ci.yml)
10[![Coverage Status](https://coveralls.io/repos/github/jaywcjlove/hotkeys/badge.svg?branch=master)](https://coveralls.io/github/jaywcjlove/hotkeys?branch=master)
11[![jaywcjlove/hotkeys-js](https://jaywcjlove.github.io/sb/lang/chinese.svg)](https://github.com/jaywcjlove/hotkeys-js/blob/master/README-zh.md)
12[![jaywcjlove/hotkeys-js](https://jaywcjlove.github.io/sb/ico/gitee.svg)](https://gitee.com/jaywcjlove/hotkeys)
13
14HotKeys.js is an input capture library with some very special features, it is easy to pick up and use, has a reasonable footprint ([~6kB](https://bundlephobia.com/result?p=hotkeys-js)) (gzipped: **`2.8kB`**), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. Official document [demo preview](https://jaywcjlove.github.io/hotkeys-js). [More examples](https://github.com/jaywcjlove/hotkeys-js/issues?q=label%3ADemo+).
15
16```bash
17╭┈┈╮ ╭┈┈╮ ╭┈┈╮
18┆ ├┈┈..┈┈┈┈┈.┆ └┈╮┆ ├┈┈..┈┈┈┈┈..┈┈.┈┈..┈┈┈┈┈.
19┆ ┆┆ □ ┆┆ ┈┤┆ < ┆ -__┘┆ ┆ ┆┆__ ┈┈┤
20╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈┈╯╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈ ┆╰┈┈┈┈┈╯
21 ╰┈┈┈┈┈╯
22```
23
24## Usage
25
26You will need `Node.js` installed on your system.
27
28```bash
29npm install hotkeys-js --save
30```
31
32```js
33import hotkeys from 'hotkeys-js';
34
35hotkeys('f5', function(event, handler){
36 // Prevent the default refresh event under WINDOWS system
37 event.preventDefault()
38 alert('you pressed F5!')
39});
40```
41
42Or manually download and link **hotkeys.js** in your HTML, It can also be downloaded via [UNPKG](https://unpkg.com/hotkeys-js/dist/):
43
44CDN: [UNPKG](https://unpkg.com/hotkeys-js/dist/) | [jsDelivr](https://cdn.jsdelivr.net/npm/hotkeys-js@3.7.3/) | [Githack](https://raw.githack.com/jaywcjlove/hotkeys/master/dist/hotkeys.min.js) | [Statically](https://cdn.statically.io/gh/jaywcjlove/hotkeys/master/dist/hotkeys.min.js) | [bundle.run](https://bundle.run/hotkeys-js@3.7.3)
45
46```html
47<script src="https://unpkg.com/hotkeys-js/dist/hotkeys.min.js"></script>
48<script type="text/javascript">
49hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
50 switch (handler.key) {
51 case 'ctrl+a': alert('you pressed ctrl+a!');
52 break;
53 case 'ctrl+b': alert('you pressed ctrl+b!');
54 break;
55 case 'r': alert('you pressed r!');
56 break;
57 case 'f': alert('you pressed f!');
58 break;
59 default: alert(event);
60 }
61});
62</script>
63```
64
65### Used in React
66
67[react-hotkeys](https://github.com/jaywcjlove/react-hotkeys) is the React component that listen to keydown and keyup keyboard events, defining and dispatching keyboard shortcuts. Detailed use method please see its documentation [react-hotkeys](https://github.com/jaywcjlove/react-hotkeys).
68
69[react-hotkeys-hook](https://github.com/JohannesKlauss/react-hotkeys-hook) - React hook for using keyboard shortcuts in components. Make sure that you have at least version 16.8 of react and react-dom installed, or otherwise hooks won't work for you.
70
71## Browser Support
72
73Hotkeys.js has been tested and should work in.
74
75```shell
76Internet Explorer 6+
77Safari
78Firefox
79Chrome
80```
81
82## Supported Keys
83
84HotKeys understands the following modifiers: `⇧`, `shift`, `option`, `⌥`, `alt`, `ctrl`, `control`, `command`, and `⌘`.
85
86The following special keys can be used for shortcuts: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete, f1 through f19, num_0 through num_9, num_multiply, num_add, num_enter, num_subtract, num_decimal, num_divide.
87
88`⌘` Command()
89`⌃` Control
90`⌥` Option(alt)
91`⇧` Shift
92`⇪` Caps Lock(Capital)
93~~`fn` Does not support fn~~
94`↩︎` return/Enter space
95
96## Defining Shortcuts
97
98One global method is exposed, key which defines shortcuts when called directly.
99
100```js
101hotkeys([keys:<String>], [option:[string|object|function]], [callback:<function>])
102```
103
104
105```js
106hotkeys('f5', function(event, handler) {
107 // Prevent the default refresh event under WINDOWS system
108 event.preventDefault();
109 alert('you pressed F5!');
110});
111
112// Returning false stops the event and prevents default browser events
113// Mac OS system defines `command + r` as a refresh shortcut
114hotkeys('ctrl+r, command+r', function() {
115 alert('stopped reload!');
116 return false;
117});
118
119// Single key
120hotkeys('a', function(event,handler){
121 //event.srcElement: input
122 //event.target: input
123 if(event.target === "input"){
124 alert('you pressed a!')
125 }
126 alert('you pressed a!')
127});
128
129// Key Combination
130hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
131 switch (handler.key) {
132 case 'ctrl+a': alert('you pressed ctrl+a!');
133 break;
134 case 'ctrl+b': alert('you pressed ctrl+b!');
135 break;
136 case 'r': alert('you pressed r!');
137 break;
138 case 'f': alert('you pressed f!');
139 break;
140 default: alert(event);
141 }
142});
143
144hotkeys('ctrl+a+s', function() {
145 alert('you pressed ctrl+a+s!');
146});
147
148// Using a scope
149hotkeys('*','wcj', function(event){
150 console.log('do something', event);
151});
152```
153
154#### option
155
156- `scope<String>`
157- `element<HTMLElement>`
158- `keyup<Boolean>`
159- `keydown<Boolean>`
160- `splitKey<string>` (default is `+`)
161- `capture<Boolean>`
162- `single<Boolean>`
163
164```js
165hotkeys('o, enter', {
166 scope: 'wcj',
167 element: document.getElementById('wrapper'),
168}, function() {
169 console.log('do something else');
170});
171
172hotkeys('ctrl-+', { splitKey: '-' }, function(e) {
173 console.log('you pressed ctrl and +');
174});
175
176hotkeys('+', { splitKey: '-' }, function(e){
177 console.log('you pressed +');
178})
179```
180
181**keyup**
182
183**key down** and **key up** both perform callback events.
184
185```js
186hotkeys('ctrl+a,alt+a+s', {keyup: true}, function(event, handler) {
187 if (event.type === 'keydown') {
188 console.log('keydown:', event.type, handler, handler.key);
189 }
190
191 if (event.type === 'keyup') {
192 console.log('keyup:', event.type, handler, handler.key);
193 }
194});
195```
196
197## API REFERENCE
198
199Asterisk "*"
200
201Modifier key judgments
202
203```js
204hotkeys('*', function() {
205 if (hotkeys.shift) {
206 console.log('shift is pressed!');
207 }
208
209 if (hotkeys.ctrl) {
210 console.log('ctrl is pressed!');
211 }
212
213 if (hotkeys.alt) {
214 console.log('alt is pressed!');
215 }
216
217 if (hotkeys.option) {
218 console.log('option is pressed!');
219 }
220
221 if (hotkeys.control) {
222 console.log('control is pressed!');
223 }
224
225 if (hotkeys.cmd) {
226 console.log('cmd is pressed!');
227 }
228
229 if (hotkeys.command) {
230 console.log('command is pressed!');
231 }
232});
233```
234
235### setScope
236
237Use the `hotkeys.setScope` method to set scope. There can only be one active scope besides 'all'. By default 'all' is always active.
238
239```js
240// Define shortcuts with a scope
241hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function() {
242 console.log('do something');
243});
244hotkeys('o, enter', 'files', function() {
245 console.log('do something else');
246});
247
248// Set the scope (only 'all' and 'issues' shortcuts will be honored)
249hotkeys.setScope('issues'); // default scope is 'all'
250```
251
252### getScope
253
254Use the `hotkeys.getScope` method to get scope.
255
256```js
257hotkeys.getScope();
258```
259
260### deleteScope
261
262Use the `hotkeys.deleteScope` method to delete a scope. This will also remove all associated hotkeys with it.
263
264```js
265hotkeys.deleteScope('issues');
266```
267You can use second argument, if need set new scope after deleting.
268
269```js
270hotkeys.deleteScope('issues', 'newScopeName');
271```
272
273### unbind
274
275Similar to defining shortcuts, they can be unbound using `hotkeys.unbind`.
276
277```js
278// unbind 'a' handler
279hotkeys.unbind('a');
280
281// Unbind a hotkeys only for a single scope
282// If no scope is specified it defaults to the current scope (hotkeys.getScope())
283hotkeys.unbind('o, enter', 'issues');
284hotkeys.unbind('o, enter', 'files');
285```
286
287Unbind events through functions.
288
289```js
290function example() {
291 hotkeys('a', example);
292 hotkeys.unbind('a', example);
293
294 hotkeys('a', 'issues', example);
295 hotkeys.unbind('a', 'issues', example);
296}
297```
298
299To unbind everything.
300
301```js
302hotkeys.unbind();
303```
304
305### isPressed
306
307For example, `hotkeys.isPressed(77)` is true if the `M` key is currently pressed.
308
309```js
310hotkeys('a', function() {
311 console.log(hotkeys.isPressed('a')); //=> true
312 console.log(hotkeys.isPressed('A')); //=> true
313 console.log(hotkeys.isPressed(65)); //=> true
314});
315```
316
317### trigger
318
319trigger shortcut key event
320
321```js
322hotkeys.trigger('ctrl+o');
323hotkeys.trigger('ctrl+o', 'scope2');
324```
325
326### getPressedKeyCodes
327
328Returns an array of key codes currently pressed.
329
330```js
331hotkeys('command+ctrl+shift+a,f', function() {
332 console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] or [70]
333})
334```
335
336### getPressedKeyString
337
338Returns an array of key codes currently pressed.
339
340```js
341hotkeys('command+ctrl+shift+a,f', function() {
342 console.log(hotkeys.getPressedKeyString()); //=> ['⌘', '⌃', '⇧', 'A', 'F']
343})
344```
345
346### getAllKeyCodes
347
348Get a list of all registration codes.
349
350```js
351hotkeys('command+ctrl+shift+a,f', function() {
352 console.log(hotkeys.getAllKeyCodes());
353 // [
354 // { scope: 'all', shortcut: 'command+ctrl+shift+a', mods: [91, 17, 16], keys: [91, 17, 16, 65] },
355 // { scope: 'all', shortcut: 'f', mods: [], keys: [42] }
356 // ]
357})
358```
359
360### filter
361
362By default hotkeys are not enabled for `INPUT` `SELECT` `TEXTAREA` elements. `Hotkeys.filter` to return to the `true` shortcut keys set to play a role, `false` shortcut keys set up failure.
363
364```js
365hotkeys.filter = function(event){
366 return true;
367}
368//How to add the filter to edit labels. <div contentEditable="true"></div>
369//"contentEditable" Older browsers that do not support drops
370hotkeys.filter = function(event) {
371 var target = event.target || event.srcElement;
372 var tagName = target.tagName;
373 return !(target.isContentEditable || tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
374}
375
376hotkeys.filter = function(event){
377 var tagName = (event.target || event.srcElement).tagName;
378 hotkeys.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
379 return true;
380}
381```
382
383### noConflict
384
385Relinquish HotKeys’s control of the `hotkeys` variable.
386
387```js
388var k = hotkeys.noConflict();
389k('a', function() {
390 console.log("do something")
391});
392
393hotkeys()
394// -->Uncaught TypeError: hotkeys is not a function(anonymous function)
395// @ VM2170:2InjectedScript._evaluateOn
396// @ VM2165:883InjectedScript._evaluateAndWrap
397// @ VM2165:816InjectedScript.evaluate @ VM2165:682
398```
399
400## Development
401
402To develop, Install dependencies, Get the code:
403
404```shell
405$ git https://github.com/jaywcjlove/hotkeys.git
406$ cd hotkeys # Into the directory
407$ npm install # or yarn install
408```
409
410To develop, run the self-reloading build:
411
412```shell
413$ npm run watch
414```
415
416Run Document Website Environment.
417
418```shell
419$ npm run doc
420```
421
422To contribute, please fork Hotkeys.js, add your patch and tests for it (in the `test/` folder) and submit a pull request.
423
424```shell
425$ npm run test
426$ npm run test:watch # Development model
427```
428
429## Contributors
430
431As always, thanks to our amazing contributors!
432
433<a href="https://github.com/jaywcjlove/hotkeys-js/graphs/contributors">
434 <img src="https://jaywcjlove.github.io/hotkeys-js/CONTRIBUTORS.svg" />
435</a>
436
437Made with [github-action-contributors](https://github.com/jaywcjlove/github-action-contributors).
438
439## License
440
441[MIT © Kenny Wong](./LICENSE)