Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
H

hotkeys-js

> 编程语言
Open source

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

7.1K stars0 likes1 views
WebsiteGitHub

About

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


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 (~8kB) (gzipped: 3.8kB), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. Official document demo preview, compatibility test. More examples.

bash
╭┈┈╮          ╭┈┈╮  ╭┈┈╮
┆  ├┈┈..┈┈┈┈┈.┆  └┈╮┆  ├┈┈..┈┈┈┈┈..┈┈.┈┈..┈┈┈┈┈.
┆     ┆┆  □  ┆┆   ┈┤┆    < ┆  -__┘┆  ┆  ┆┆__ ┈┈┤
╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈┈╯╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈  ┆╰┈┈┈┈┈╯
                                  ╰┈┈┈┈┈╯

Usage

You will need Node.js installed on your system.

bash
npm install hotkeys-js --save
javascript
import hotkeys from 'hotkeys-js';

hotkeys('f5', function(event, handler){
  // Prevent the default refresh event under WINDOWS system
  event.preventDefault()
  alert('you pressed F5!')
});

Browser Usage

Or manually download and link hotkeys.js in your HTML. The library provides different formats for different use cases:

CDN Links: UNPKG | jsDelivr | Githack | Statically

Available Formats:

IIFE (Immediately Invoked Function Expression) - Recommended for direct browser usage:

xml
<script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.min.js">
</script>
<script type="text/javascript">
hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
  switch (handler.key) {
    case 'ctrl+a': alert('you pressed ctrl+a!');
      break;
    case 'ctrl+b': alert('you pressed ctrl+b!');
      break;
    case 'r': alert('you pressed r!');
      break;
    case 'f': alert('you pressed f!');
      break;
    default: alert(event);
  }
});
</script>

UMD (Universal Module Definition) - For CommonJS/AMD environments:

xml
<script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.umd.cjs">
</script>

ES Module - For modern browsers with module support:

xml
<script type="module">
import hotkeys from 'https://unpkg.com/hotkeys-js/dist/hotkeys-js.js';
hotkeys('ctrl+a', function(event, handler){
  alert('you pressed ctrl+a!');
});
</script>

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.

bash
Internet Explorer 6+
Safari
Firefox
Chrome

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.

…
…

option

  • scope<String>: Sets the scope in which the shortcut key is active
  • element<HTMLElement>: Specifies the DOM element to bind the event to
  • keyup<Boolean>: Whether to trigger the shortcut on key release
  • keydown<Boolean>: Whether to trigger the shortcut on key press
  • splitKey<String>: Delimiter for key combinations (default is +)
  • capture<Boolean>: Whether to trigger the listener during the capture phase (before the event bubbles down)
  • single<Boolean>: Allows only one callback function (automatically unbinds previous one)
javascript
hotkeys('o, enter', {
  scope: 'wcj',
  element: document.getElementById('wrapper'),
}, function() {
  console.log('do something else');
});

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

hotkeys('+', { splitKey: '-' }, function(e){
  console.log('you pressed +');
})

keyup

key down and key up both perform callback events.

javascript
hotkeys('ctrl+a,alt+a+s', {keyup: true}, function(event, handler) {
  if (event.type === 'keydown') {
    console.log('keydown:', event.type, handler, handler.key);
  }

  if (event.type === 'keyup') {
    console.log('keyup:', event.type, handler, handler.key);
  }
});

API REFERENCE

Asterisk "*"

Modifier key judgments

javascript
hotkeys('*', function() {
  if (hotkeys.shift) {
    console.log('shift is pressed!');
  }

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

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

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

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

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

  if (hotkeys.command) {
    console.log('command is pressed!');
  }
});

setScope

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

javascript
// Define shortcuts with a scope
hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function() {
  console.log('do something');
});
hotkeys('o, enter', 'files', function() {
  console.log('do something else');
});

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

getScope

Use the hotkeys.getScope method to get scope.

javascript
hotkeys.getScope();

deleteScope

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

javascript
hotkeys.deleteScope('issues');

You can use second argument, if need set new scope after deleting.

javascript
hotkeys.deleteScope('issues', 'newScopeName');

unbind

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

javascript
// unbind 'a' handler
hotkeys.unbind('a');

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

Unbind events through functions.

javascript
function example() {
  hotkeys('a', example);
  hotkeys.unbind('a', example);

  hotkeys('a', 'issues', example);
  hotkeys.unbind('a', 'issues', example);
}

To unbind everything.

javascript
hotkeys.unbind();

isPressed

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

javascript
hotkeys('a', function() {
  console.log(hotkeys.isPressed('a')); //=> true
  console.log(hotkeys.isPressed('A')); //=> true
  console.log(hotkeys.isPressed(65)); //=> true
});

trigger

trigger shortcut key event

javascript
hotkeys.trigger('ctrl+o');
hotkeys.trigger('ctrl+o', 'scope2');

getPressedKeyCodes

Returns an array of key codes currently pressed.

javascript
hotkeys('command+ctrl+shift+a,f', function() {
  console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] or [70]
})

getPressedKeyString

Returns an array of key codes currently pressed.

javascript
hotkeys('command+ctrl+shift+a,f', function() {
  console.log(hotkeys.getPressedKeyString()); 
  //=> ['⌘', '⌃', '⇧', 'A', 'F']
})

getAllKeyCodes

Get a list of all registration codes.

javascript
hotkeys('command+ctrl+shift+a,f', function() {
  console.log(hotkeys.getAllKeyCodes());
  // [
  //   { 
  //      scope: 'all', 
  //      shortcut: 'command+ctrl+shift+a', 
  //      mods: [91, 17, 16], 
  //      keys: [91, 17, 16, 65] 
  //    },
  //   { scope: 'all', shortcut: 'f', mods: [], keys: [42] }
  // ]
})

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.

…

noConflict

Relinquish HotKeys’s control of the hotkeys variable.

javascript
var k = hotkeys.noConflict();
k('a', function() {
  console.log("do something")
});

hotkeys()
// -->Uncaught TypeError: hotkeys is not a function(anonymous function)
// @ VM2170:2InjectedScript._evaluateOn
// @ VM2165:883InjectedScript._evaluateAndWrap
// @ VM2165:816InjectedScript.evaluate @ VM2165:682

Development

To develop, Install dependencies, Get the code:

bash
$ git https://github.com/jaywcjlove/hotkeys.git
$ cd hotkeys     # Into the directory
$ npm install    # or  yarn install

To develop, run the self-reloading build:

bash
$ npm run watch

Run Document Website Environment.

bash
# Generate documentation website
$ npm run doc 
# Live-generate documentation website
$ npm run start 

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

bash
$ npm run test
$ npm run test:watch # Development model

Contributors

As always, thanks to our amazing contributors!

Made with action-contributors.

Special thanks to @dimensi for the refactoring of version 4.0.

License

MIT © Kenny Wong

Issues· 159 open

View all issuesOpen on GitHub
  • #467

    Can Supported Keys be customized?

    Updated Jul 17, 2026
  • #539

    v4 letter-key dispatch breaks Dvorak/Colemak layouts (no opt-out)

    Updated Apr 30, 2026
  • #521

    _hotkeysJs.default is not a function

    Updated Apr 6, 2026
  • #523

    [nit] There is a tiny breaking change in the typescript api when going from version 3 to 4.

    Updated Jan 2, 2026
  • #522

    How to bind the hoktey in one vue component(when leave this comp it will inactive)?

    Updated Nov 26, 2025
  • #313

    hotkeys 4.0, Based on TypeScript.

    Updated Nov 23, 2025
  • #509

    Hotkeys not working after triggering print dialog

    Updated Sep 1, 2025
  • #516

    have "preventDefault()" and "stopPropagation()" ?

    Updated Sep 1, 2025
  • #215

    pause and resume functionality

    Updated Jul 9, 2025
  • #513

    Triggering a custom key function requires the same code to be executed at the end

    Updated May 10, 2025

> Tags

TypeScriptbrowserhotkeyhotkeysjavascript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 22, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言