UNPKG

11.3 kBMarkdownView Raw
1# Hotkeys
2
3<!--dividing-->
4
5[![CDN jsdelivr](https://data.jsdelivr.com/v1/package/npm/hotkeys-js/badge?style=rounded)](https://www.jsdelivr.com/package/npm/hotkeys-js)
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.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/actions/workflows/ci.yml/badge.svg)](https://github.com/jaywcjlove/hotkeys/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](https://jaywcjlove.github.io/sb/lang/chinese.svg)](https://github.com/jaywcjlove/hotkeys/blob/master/README-zh.md)
12[![jaywcjlove/hotkeys](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 ([~3kb](https://bundlephobia.com/result?p=hotkeys-js)) (gzipped: 1.73kb), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. Official document [demo preview](http://jaywcjlove.github.io/hotkeys). [More examples](https://github.com/jaywcjlove/hotkeys/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
29$ npm 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
163```js
164hotkeys('o, enter', {
165 scope: 'wcj',
166 element: document.getElementById('wrapper'),
167}, function(){
168 console.log('do something else');
169});
170
171hotkeys('ctrl-+', { splitKey: '-' }, function(e) {
172 console.log('you pressed ctrl and +');
173});
174
175hotkeys('+', { splitKey: '-' }, function(e){
176 console.log('you pressed +');
177})
178```
179
180**keyup**
181
182**key down** and **key up** both perform callback events.
183
184```js
185hotkeys('ctrl+a,alt+a+s', {keyup: true}, function(event, handler) {
186 if (event.type === 'keydown') {
187 console.log('keydown:', event.type, handler, handler.key);
188 }
189
190 if (event.type === 'keyup') {
191 console.log('keyup:', event.type, handler, handler.key);
192 }
193});
194```
195
196## API REFERENCE
197
198Asterisk "*"
199
200Modifier key judgments
201
202```js
203hotkeys('*', function() {
204 if (hotkeys.shift) {
205 console.log('shift is pressed!');
206 }
207
208 if (hotkeys.ctrl) {
209 console.log('ctrl is pressed!');
210 }
211
212 if (hotkeys.alt) {
213 console.log('alt is pressed!');
214 }
215
216 if (hotkeys.option) {
217 console.log('option is pressed!');
218 }
219
220 if (hotkeys.control) {
221 console.log('control is pressed!');
222 }
223
224 if (hotkeys.cmd) {
225 console.log('cmd is pressed!');
226 }
227
228 if (hotkeys.command) {
229 console.log('command is pressed!');
230 }
231});
232```
233
234### setScope
235
236Use the `hotkeys.setScope` method to set scope. There can only be one active scope besides 'all'. By default 'all' is always active.
237
238```js
239// Define shortcuts with a scope
240hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function(){
241 console.log('do something');
242});
243hotkeys('o, enter', 'files', function(){
244 console.log('do something else');
245});
246
247// Set the scope (only 'all' and 'issues' shortcuts will be honored)
248hotkeys.setScope('issues'); // default scope is 'all'
249```
250
251### getScope
252
253Use the `hotkeys.getScope` method to get scope.
254
255```js
256hotkeys.getScope();
257```
258
259### deleteScope
260
261Use the `hotkeys.deleteScope` method to delete a scope. This will also remove all associated hotkeys with it.
262
263```js
264hotkeys.deleteScope('issues');
265```
266You can use second argument, if need set new scope after deleting.
267
268```js
269hotkeys.deleteScope('issues', 'newScopeName');
270```
271
272### unbind
273
274Similar to defining shortcuts, they can be unbound using `hotkeys.unbind`.
275
276```js
277// unbind 'a' handler
278hotkeys.unbind('a');
279
280// Unbind a hotkeys only for a single scope
281// If no scope is specified it defaults to the current scope (hotkeys.getScope())
282hotkeys.unbind('o, enter', 'issues');
283hotkeys.unbind('o, enter', 'files');
284```
285
286Unbind events through functions.
287
288```js
289function example() {
290 hotkeys('a', example);
291 hotkeys.unbind('a', example);
292
293 hotkeys('a', 'issues', example);
294 hotkeys.unbind('a', 'issues', example);
295}
296```
297
298To unbind everything.
299
300```js
301hotkeys.unbind();
302```
303
304### isPressed
305
306For example, `hotkeys.isPressed(77)` is true if the `M` key is currently pressed.
307
308```js
309hotkeys('a', function() {
310 console.log(hotkeys.isPressed('a')); //=> true
311 console.log(hotkeys.isPressed('A')); //=> true
312 console.log(hotkeys.isPressed(65)); //=> true
313});
314```
315
316### trigger
317
318```js
319hotkeys.trigger('ctrl+o');
320hotkeys.trigger('ctrl+o', 'scope2');
321```
322
323### getPressedKeyCodes
324
325Returns an array of key codes currently pressed.
326
327```js
328hotkeys('command+ctrl+shift+a,f', function(){
329 console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] or [70]
330})
331```
332
333### filter
334
335By 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.
336
337```js
338hotkeys.filter = function(event){
339 return true;
340}
341//How to add the filter to edit labels. <div contentEditable="true"></div>
342//"contentEditable" Older browsers that do not support drops
343hotkeys.filter = function(event) {
344 var target = event.target || event.srcElement;
345 var tagName = target.tagName;
346 return !(target.isContentEditable || tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
347}
348
349hotkeys.filter = function(event){
350 var tagName = (event.target || event.srcElement).tagName;
351 hotkeys.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
352 return true;
353}
354```
355
356### noConflict
357
358Relinquish HotKeys’s control of the `hotkeys` variable.
359
360```js
361var k = hotkeys.noConflict();
362k('a', function() {
363 console.log("do something")
364});
365
366hotkeys()
367// -->Uncaught TypeError: hotkeys is not a function(anonymous function)
368// @ VM2170:2InjectedScript._evaluateOn
369// @ VM2165:883InjectedScript._evaluateAndWrap
370// @ VM2165:816InjectedScript.evaluate @ VM2165:682
371```
372
373## Development
374
375To develop, Install dependencies, Get the code:
376
377```shell
378$ git https://github.com/jaywcjlove/hotkeys.git
379$ cd hotkeys # Into the directory
380$ npm install # or yarn install
381```
382
383To develop, run the self-reloading build:
384
385```shell
386$ npm run watch
387```
388
389Run Document Website Environment.
390
391```shell
392$ npm run doc
393```
394
395To contribute, please fork Hotkeys.js, add your patch and tests for it (in the `test/` folder) and submit a pull request.
396
397```shell
398$ npm run test
399$ npm run test:watch # Development model
400```
401
402## Contributors
403
404As always, thanks to our amazing contributors!
405
406<a href="https://github.com/jaywcjlove/hotkeys/graphs/contributors">
407 <img src="https://jaywcjlove.github.io/hotkeys/CONTRIBUTORS.svg" />
408</a>
409
410Made with [github-action-contributors](https://github.com/jaywcjlove/github-action-contributors).
411
412## License
413
414[MIT © Kenny Wong](./LICENSE)