hotkeys-js
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Top Related Projects
Simple library for handling keyboard shortcuts in Javascript
A keyboard input capturing utility in which any key can be a modifier key.
A tiny (~650 B) & modern library for keybindings.
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
Quick Overview
Hotkeys-js is a lightweight JavaScript library for capturing keyboard input in web applications. It allows developers to easily bind and manage keyboard shortcuts, supporting various key combinations and modifiers across different browsers and operating systems.
Pros
- Simple and intuitive API for binding keyboard shortcuts
- Lightweight with no dependencies, making it easy to integrate into projects
- Supports complex key combinations and modifiers (e.g., Ctrl+Shift+A)
- Cross-browser compatible, including support for older browsers
Cons
- Limited advanced features compared to some more comprehensive keyboard libraries
- Documentation could be more extensive, especially for edge cases and advanced usage
- Potential conflicts with browser default shortcuts if not managed carefully
- No built-in support for handling conflicting shortcuts within the application
Code Examples
Binding a simple shortcut:
hotkeys('ctrl+a', function(event, handler) {
event.preventDefault();
alert('You pressed Ctrl+A!');
});
Binding multiple shortcuts to the same function:
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;
}
});
Unbinding a shortcut:
hotkeys.unbind('ctrl+a');
Getting Started
- Install the library using npm:
npm install hotkeys-js
- Import the library in your JavaScript file:
import hotkeys from 'hotkeys-js';
- Start binding keyboard shortcuts:
hotkeys('ctrl+s', function(event, handler) {
event.preventDefault();
console.log('You pressed Ctrl+S!');
});
That's it! You can now start using hotkeys-js to capture keyboard input in your web application.
Competitor Comparisons
Simple library for handling keyboard shortcuts in Javascript
Pros of Mousetrap
- More mature and established library with a longer history
- Supports a wider range of browsers, including older versions
- Has a slightly smaller file size, which can be beneficial for performance
Cons of Mousetrap
- Less actively maintained, with fewer recent updates
- Lacks some advanced features present in hotkeys-js, such as custom key combinations
- Does not support some modern development practices like ES6 modules out of the box
Code Comparison
Mousetrap:
Mousetrap.bind('ctrl+s', function(e) {
e.preventDefault();
// Save functionality
});
hotkeys-js:
hotkeys('ctrl+s', function(event, handler) {
event.preventDefault();
// Save functionality
});
Both libraries offer similar syntax for binding key combinations to functions. The main difference lies in the function parameters and how they handle the event object. Mousetrap passes the event directly, while hotkeys-js provides both the event and a handler object.
Overall, Mousetrap is a solid choice for projects requiring broad browser support and a lightweight solution. However, hotkeys-js offers more modern features and active development, making it potentially better suited for newer projects with more complex keyboard interaction requirements.
A keyboard input capturing utility in which any key can be a modifier key.
Pros of Keypress
- More extensive documentation and examples
- Supports complex key combinations and sequences
- Allows for custom key mappings and aliases
Cons of Keypress
- Less actively maintained (last update in 2016)
- Larger file size compared to hotkeys-js
- May have compatibility issues with modern browsers
Code Comparison
Keypress:
var listener = new window.keypress.Listener();
listener.simple_combo("shift s", function() {
console.log("You pressed shift and s");
});
hotkeys-js:
hotkeys('shift+s', function(event, handler) {
console.log("You pressed shift and s");
});
Both libraries offer similar functionality for binding key combinations, but Keypress uses a more object-oriented approach with a Listener instance, while hotkeys-js provides a more straightforward function call. hotkeys-js has a simpler syntax and is more lightweight, making it easier to integrate into projects. However, Keypress offers more advanced features for complex key combinations and sequences, which may be beneficial for applications requiring intricate keyboard interactions.
A tiny (~650 B) & modern library for keybindings.
Pros of tinykeys
- Smaller bundle size (1.5KB vs 5KB for hotkeys-js)
- Simpler API with a more functional approach
- Better TypeScript support out of the box
Cons of tinykeys
- Less feature-rich compared to hotkeys-js
- Limited browser support (modern browsers only)
- Fewer customization options for key combinations
Code Comparison
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Shift+D": () => {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
},
});
hotkeys-js:
import hotkeys from "hotkeys-js";
hotkeys("shift+d", function(event, handler) {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
});
Both libraries offer straightforward ways to bind key combinations to functions, but tinykeys uses a more object-oriented approach, while hotkeys-js uses a string-based syntax for defining shortcuts. tinykeys provides a cleaner, more modern API, but hotkeys-js offers more flexibility and features for complex keyboard shortcut scenarios.
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
Pros of keymaster
- Lightweight and simple to use
- Supports key sequences and key combinations
- Works across different browsers and platforms
Cons of keymaster
- Less actively maintained (last update in 2016)
- Fewer features compared to hotkeys-js
- Limited documentation and examples
Code Comparison
keymaster:
key('⌘+r, ctrl+r', function() {
alert('refreshing page');
});
hotkeys-js:
hotkeys('ctrl+r, command+r', function(event, handler) {
alert('refreshing page');
});
Both libraries offer similar syntax for defining keyboard shortcuts. However, hotkeys-js provides more advanced features and better documentation, making it easier to implement complex keyboard interactions. keymaster's simplicity may be preferred for basic use cases, but its lack of recent updates could be a concern for long-term maintainability.
hotkeys-js offers additional features like:
- Scope management
- Filtering based on input types
- More extensive event handling
While keymaster is more focused on providing a straightforward API for basic keyboard shortcut functionality. The choice between the two depends on the specific requirements of your project and the level of complexity needed in keyboard shortcut management.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
Pros of KeyboardJS
- More extensive API with additional features like key sequences and combos
- Better support for international keyboard layouts
- More active development and maintenance
Cons of KeyboardJS
- Larger file size and potentially higher overhead
- Steeper learning curve due to more complex API
- Less straightforward implementation for simple use cases
Code Comparison
hotkeys-js:
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;
}
});
KeyboardJS:
KeyboardJS.bind('ctrl + a', function(e) {
console.log('ctrl+a pressed');
});
KeyboardJS.bind('ctrl + b', function(e) {
console.log('ctrl+b pressed');
});
KeyboardJS.bind('r', function(e) {
console.log('r pressed');
});
Both libraries offer similar functionality for binding keyboard shortcuts, but KeyboardJS provides a more granular approach with separate bind calls for each shortcut. hotkeys-js allows for a more compact syntax when defining multiple shortcuts at once.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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 (~6kB) (gzipped: 2.8kB
), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks. Official document demo preview. More examples.
ââââ® ââââ® ââââ®
â âââ..âââââ.â âââ®â âââ..âââââ..ââ.ââ..âââââ.
â ââ â¡ ââ ââ¤â < â -__ââ â ââ__ âââ¤
â°âââ´âââ¯â°ââââââ¯â°âââââ¯â°âââ´âââ¯â°ââââââ¯â°âââ ââ°ââââââ¯
â°ââââââ¯
Usage
You will need Node.js
installed on your system.
npm install hotkeys-js --save
import hotkeys from 'hotkeys-js';
hotkeys('f5', function(event, handler){
// Prevent the default refresh event under WINDOWS system
event.preventDefault()
alert('you pressed F5!')
});
Or manually download and link hotkeys.js in your HTML, It can also be downloaded via UNPKG:
CDN: UNPKG | jsDelivr | Githack | Statically | bundle.run
<script src="https://unpkg.com/hotkeys-js/dist/hotkeys.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>
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.
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.
hotkeys([keys:<String>], [option:[string|object|function]], [callback:<function>])
hotkeys('f5', function(event, handler) {
// Prevent the default refresh event under WINDOWS system
event.preventDefault();
alert('you pressed F5!');
});
// Returning false stops the event and prevents default browser events
// Mac OS system defines `command + r` as a refresh shortcut
hotkeys('ctrl+r, command+r', function() {
alert('stopped reload!');
return false;
});
// Single key
hotkeys('a', function(event,handler){
//event.srcElement: input
//event.target: input
if(event.target === "input"){
alert('you pressed a!')
}
alert('you pressed a!')
});
// Key Combination
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);
}
});
hotkeys('ctrl+a+s', function() {
alert('you pressed ctrl+a+s!');
});
// Using a scope
hotkeys('*','wcj', function(event){
console.log('do something', event);
});
option
scope<String>
element<HTMLElement>
keyup<Boolean>
keydown<Boolean>
splitKey<string>
(default is+
)capture<Boolean>
single<Boolean>
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.
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
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.
// 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.
hotkeys.getScope();
deleteScope
Use the hotkeys.deleteScope
method to delete a scope. This will also remove all associated hotkeys with it.
hotkeys.deleteScope('issues');
You can use second argument, if need set new scope after deleting.
hotkeys.deleteScope('issues', 'newScopeName');
unbind
Similar to defining shortcuts, they can be unbound using hotkeys.unbind
.
// 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.
function example() {
hotkeys('a', example);
hotkeys.unbind('a', example);
hotkeys('a', 'issues', example);
hotkeys.unbind('a', 'issues', example);
}
To unbind everything.
hotkeys.unbind();
isPressed
For example, hotkeys.isPressed(77)
is true if the M
key is currently pressed.
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
hotkeys.trigger('ctrl+o');
hotkeys.trigger('ctrl+o', 'scope2');
getPressedKeyCodes
Returns an array of key codes currently pressed.
hotkeys('command+ctrl+shift+a,f', function() {
console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] or [70]
})
getPressedKeyString
Returns an array of key codes currently pressed.
hotkeys('command+ctrl+shift+a,f', function() {
console.log(hotkeys.getPressedKeyString()); //=> ['â', 'â', 'â§', 'A', 'F']
})
getAllKeyCodes
Get a list of all registration codes.
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.
hotkeys.filter = function(event){
return true;
}
//How to add the filter to edit labels. <div contentEditable="true"></div>
//"contentEditable" Older browsers that do not support drops
hotkeys.filter = function(event) {
var target = event.target || event.srcElement;
var tagName = target.tagName;
return !(target.isContentEditable || tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
hotkeys.filter = function(event){
var tagName = (event.target || event.srcElement).tagName;
hotkeys.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
return true;
}
noConflict
Relinquish HotKeysâs control of the hotkeys
variable.
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:
$ git https://github.com/jaywcjlove/hotkeys.git
$ cd hotkeys # Into the directory
$ npm install # or yarn install
To develop, run the self-reloading build:
$ npm run watch
Run Document Website Environment.
$ npm run doc
To contribute, please fork Hotkeys.js, add your patch and tests for it (in the test/
folder) and submit a pull request.
$ npm run test
$ npm run test:watch # Development model
Contributors
As always, thanks to our amazing contributors!
Made with github-action-contributors.
License
Top Related Projects
Simple library for handling keyboard shortcuts in Javascript
A keyboard input capturing utility in which any key can be a modifier key.
A tiny (~650 B) & modern library for keybindings.
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot