Hotkeys

➷ A robust Javascript library for capturing keyboard input. It has no depen...

README

Hotkeys


CDN jsdelivr undefined undefined
no dependencies GitHub Actions CI Coverage Status jaywcjlove/hotkeys jaywcjlove/hotkeys

HotKeys.js is an input capture library with some very special features, it is easy to pick up and use, has a reasonable footprint (~3kb) (gzipped: 1.73kb), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. Official document demo preview. More examples.

  1. ``` sh
  2.             
  3.   ...    ........
  4.                 <   -__    __
  5.   
  6.                                   
  7. ```

Usage


You will need Node.js installed on your system.

  1. ``` sh
  2. $ npm install hotkeys-js --save
  3. ```

  1. ``` js
  2. import hotkeys from 'hotkeys-js';

  3. hotkeys('f5', function(event, handler){
  4.   // Prevent the default refresh event under WINDOWS system
  5.   event.preventDefault()
  6.   alert('you pressed F5!')
  7. });
  8. ```

Or manually download and link hotkeys.js in your HTML, It can also be downloaded via UNPKG:


  1. ``` html
  2. <script src="https://unpkg.com/hotkeys-js/dist/hotkeys.min.js"></script>
  3. <script type="text/javascript">
  4. hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
  5.   switch (handler.key) {
  6.     case 'ctrl+a': alert('you pressed ctrl+a!');
  7.       break;
  8.     case 'ctrl+b': alert('you pressed ctrl+b!');
  9.       break;
  10.     case 'r': alert('you pressed r!');
  11.       break;
  12.     case 'f': alert('you pressed f!');
  13.       break;
  14.     default: alert(event);
  15.   }
  16. });
  17. </script>
  18. ```

Used in React


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.

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.

Browser Support


Hotkeys.js has been tested and should work in.

  1. ``` sh
  2. Internet Explorer 6+
  3. Safari
  4. Firefox
  5. Chrome
  6. ```

Supported Keys


HotKeys understands the following modifiers: , shift, option, , alt, ctrl, control, command, and .

The 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.

Command()
Control
Option(alt)
Shift
Caps Lock(Capital)
fn Does not support fn
↩︎ return/Enter space

Defining Shortcuts


One global method is exposed, key which defines shortcuts when called directly.

  1. ``` js
  2. hotkeys([keys:<String>], [option:[string|object|function]], [callback:<function>])
  3. ```

  1. ``` js
  2. hotkeys('f5', function(event, handler) {
  3.   // Prevent the default refresh event under WINDOWS system
  4.   event.preventDefault();
  5.   alert('you pressed F5!');
  6. });

  7. // Returning false stops the event and prevents default browser events
  8. // Mac OS system defines `command + r` as a refresh shortcut
  9. hotkeys('ctrl+r, command+r', function() {
  10.   alert('stopped reload!');
  11.   return false;
  12. });

  13. // Single key
  14. hotkeys('a', function(event,handler){
  15.   //event.srcElement: input
  16.   //event.target: input
  17.   if(event.target === "input"){
  18.       alert('you pressed a!')
  19.   }
  20.   alert('you pressed a!')
  21. });

  22. // Key Combination
  23. hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
  24.   switch (handler.key) {
  25.     case 'ctrl+a': alert('you pressed ctrl+a!');
  26.       break;
  27.     case 'ctrl+b': alert('you pressed ctrl+b!');
  28.       break;
  29.     case 'r': alert('you pressed r!');
  30.       break;
  31.     case 'f': alert('you pressed f!');
  32.       break;
  33.     default: alert(event);
  34.   }
  35. });

  36. hotkeys('ctrl+a+s', function() {
  37.     alert('you pressed ctrl+a+s!');
  38. });

  39. // Using a scope
  40. hotkeys('*','wcj', function(event){
  41.   console.log('do something', event);
  42. });
  43. ```

option


- `scope`- `element`- `keyup`- `keydown`- `splitKey` (default is `+`)- `capture`

  1. ``` js
  2. hotkeys('o, enter', {
  3.   scope: 'wcj',
  4.   element: document.getElementById('wrapper'),
  5. }, function(){
  6.   console.log('do something else');
  7. });

  8. hotkeys('ctrl-+', { splitKey: '-' }, function(e) {
  9.   console.log('you pressed ctrl and +');
  10. });

  11. hotkeys('+', { splitKey: '-' }, function(e){
  12.   console.log('you pressed +');
  13. })
  14. ```

keyup

key down and key up both perform callback events.

  1. ``` js
  2. hotkeys('ctrl+a,alt+a+s', {keyup: true}, function(event, handler) {
  3.   if (event.type === 'keydown') {
  4.     console.log('keydown:', event.type, handler, handler.key);
  5.   }

  6.   if (event.type === 'keyup') {
  7.     console.log('keyup:', event.type, handler, handler.key);
  8.   }
  9. });
  10. ```

API REFERENCE


Asterisk "*"

Modifier key judgments

  1. ``` js
  2. hotkeys('*', function() {
  3.   if (hotkeys.shift) {
  4.     console.log('shift is pressed!');
  5.   }

  6.   if (hotkeys.ctrl) {
  7.     console.log('ctrl is pressed!');
  8.   }

  9.   if (hotkeys.alt) {
  10.     console.log('alt is pressed!');
  11.   }

  12.   if (hotkeys.option) {
  13.     console.log('option is pressed!');
  14.   }

  15.   if (hotkeys.control) {
  16.     console.log('control is pressed!');
  17.   }

  18.   if (hotkeys.cmd) {
  19.     console.log('cmd is pressed!');
  20.   }

  21.   if (hotkeys.command) {
  22.     console.log('command is pressed!');
  23.   }
  24. });
  25. ```

setScope


Use the hotkeys.setScope method to set scope. There can only be one active scope besides 'all'.  By default 'all' is always active.

  1. ``` js
  2. // Define shortcuts with a scope
  3. hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function(){
  4.   console.log('do something');
  5. });
  6. hotkeys('o, enter', 'files', function(){
  7.   console.log('do something else');
  8. });

  9. // Set the scope (only 'all' and 'issues' shortcuts will be honored)
  10. hotkeys.setScope('issues'); // default scope is 'all'
  11. ```

getScope


Use the hotkeys.getScope method to get scope.

  1. ``` js
  2. hotkeys.getScope();
  3. ```

deleteScope


Use the hotkeys.deleteScope method to delete a scope. This will also remove all associated hotkeys with it.

  1. ``` js
  2. hotkeys.deleteScope('issues');
  3. ```
You can use second argument, if need set new scope after deleting.

  1. ``` js
  2. hotkeys.deleteScope('issues', 'newScopeName');
  3. ```

unbind


Similar to defining shortcuts, they can be unbound using hotkeys.unbind.

  1. ``` js
  2. // unbind 'a' handler
  3. hotkeys.unbind('a');

  4. // Unbind a hotkeys only for a single scope
  5. // If no scope is specified it defaults to the current scope (hotkeys.getScope())
  6. hotkeys.unbind('o, enter', 'issues');
  7. hotkeys.unbind('o, enter', 'files');
  8. ```

Unbind events through functions.

  1. ``` js
  2. function example() {
  3.   hotkeys('a', example);
  4.   hotkeys.unbind('a', example);

  5.   hotkeys('a', 'issues', example);
  6.   hotkeys.unbind('a', 'issues', example);
  7. }
  8. ```

To unbind everything.

  1. ``` js
  2. hotkeys.unbind();
  3. ```

isPressed


For example, hotkeys.isPressed(77) is true if the M key is currently pressed.

  1. ``` js
  2. hotkeys('a', function() {
  3.   console.log(hotkeys.isPressed('a')); //=> true
  4.   console.log(hotkeys.isPressed('A')); //=> true
  5.   console.log(hotkeys.isPressed(65)); //=> true
  6. });
  7. ```

trigger


  1. ``` js
  2. hotkeys.trigger('ctrl+o');
  3. hotkeys.trigger('ctrl+o', 'scope2');
  4. ```

getPressedKeyCodes


Returns an array of key codes currently pressed.

  1. ``` js
  2. hotkeys('command+ctrl+shift+a,f', function(){
  3.   console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] or [70]
  4. })
  5. ```

getPressedKeyStrings


Returns an array of key codes currently pressed.

  1. ``` js
  2. hotkeys('command+ctrl+shift+a,f', function(){
  3.   console.log(hotkeys.getPressedKeyString()); //=> ['⌘', '⌃', '⇧', 'A', 'F']
  4. })
  5. ```

filter


By 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.

  1. ``` js
  2. hotkeys.filter = function(event){
  3.   return true;
  4. }
  5. //How to add the filter to edit labels.
  6. //"contentEditable" Older browsers that do not support drops
  7. hotkeys.filter = function(event) {
  8.   var target = event.target || event.srcElement;
  9.   var tagName = target.tagName;
  10.   return !(target.isContentEditable || tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
  11. }

  12. hotkeys.filter = function(event){
  13.   var tagName = (event.target || event.srcElement).tagName;
  14.   hotkeys.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
  15.   return true;
  16. }
  17. ```

noConflict


Relinquish HotKeys’s control of the hotkeys variable.

  1. ``` js
  2. var k = hotkeys.noConflict();
  3. k('a', function() {
  4.   console.log("do something")
  5. });

  6. hotkeys()
  7. // -->Uncaught TypeError: hotkeys is not a function(anonymous function)
  8. // @ VM2170:2InjectedScript._evaluateOn
  9. // @ VM2165:883InjectedScript._evaluateAndWrap
  10. // @ VM2165:816InjectedScript.evaluate @ VM2165:682
  11. ```

Development


To develop, Install dependencies, Get the code:

  1. ``` sh
  2. $ git https://github.com/jaywcjlove/hotkeys.git
  3. $ cd hotkeys     # Into the directory
  4. $ npm install    # or  yarn install
  5. ```

To develop, run the self-reloading build:

  1. ``` sh
  2. $ npm run watch
  3. ```

Run Document Website Environment.

  1. ``` sh
  2. $ npm run doc
  3. ```

To contribute, please fork Hotkeys.js, add your patch and tests for it (in the test/ folder) and submit a pull request.

  1. ``` sh
  2. $ npm run test
  3. $ npm run test:watch # Development model
  4. ```

Contributors


As always, thanks to our amazing contributors!



License