keymaster
A simple micro-library for defining and dispatching keyboard shortcuts. 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 robust Javascript library for capturing keyboard input. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
Quick Overview
Keymaster is a lightweight JavaScript library for defining and dispatching keyboard shortcuts in web applications. It provides a simple and flexible way to handle keyboard events, allowing developers to easily add keyboard navigation and shortcuts to their web projects.
Pros
- Lightweight and dependency-free
- Easy to use and integrate into existing projects
- Supports key combinations and sequences
- Works across different browsers and platforms
Cons
- Limited advanced features compared to more comprehensive libraries
- Not actively maintained (last update was in 2018)
- Lacks TypeScript support out of the box
- May conflict with browser or OS shortcuts if not carefully implemented
Code Examples
- Basic key binding:
key('ctrl+shift+p', function() {
console.log('Control+Shift+P shortcut triggered');
});
- Binding multiple keys to the same action:
key('⌘+r, ctrl+r', function() {
console.log('Refresh action triggered');
});
- Using key sequences:
key('↑ ↑ ↓ ↓ ← → ← → b a', function() {
console.log('Konami code activated!');
});
- Scoping shortcuts to specific elements:
key('a', 'issues', function() {
console.log('A pressed in issues scope');
});
key.setScope('issues');
Getting Started
To use Keymaster in your project, follow these steps:
- Include the Keymaster script in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/keymaster/1.6.1/keymaster.min.js"></script>
- Start defining your keyboard shortcuts in your JavaScript code:
key('ctrl+s', function() {
saveDocument();
return false; // Prevent default browser behavior
});
key('⌘+f, ctrl+f', function() {
searchDocument();
});
// Define a shortcut in a specific scope
key('a', 'admin', function() {
console.log('Admin shortcut activated');
});
// Set the current scope
key.setScope('admin');
That's it! You can now start using Keymaster to handle keyboard shortcuts in your web application.
Competitor Comparisons
Simple library for handling keyboard shortcuts in Javascript
Pros of Mousetrap
- More comprehensive documentation and examples
- Supports binding to specific elements, not just global bindings
- Actively maintained with recent updates
Cons of Mousetrap
- Slightly larger file size (4.8KB vs 4.0KB minified)
- May have a steeper learning curve for simple use cases
- Requires more setup for basic key binding scenarios
Code Comparison
Keymaster:
key('⌘+r, ctrl+r', function() {
alert('refreshing page');
});
Mousetrap:
Mousetrap.bind(['command+r', 'ctrl+r'], function() {
alert('refreshing page');
});
Both libraries offer similar syntax for basic key bindings, with Mousetrap using an array for multiple key combinations. Mousetrap provides more advanced features like binding to specific elements:
Mousetrap(element).bind('4', function() {
console.log('4 pressed on element');
});
Overall, Mousetrap offers more features and flexibility, while Keymaster provides a simpler API for basic key binding needs. The choice between the two depends on the specific requirements of your project and the level of complexity you need in handling keyboard events.
A keyboard input capturing utility in which any key can be a modifier key.
Pros of Keypress
- More extensive documentation and examples
- Supports key sequences and combos out of the box
- Allows for more granular control over key events
Cons of Keypress
- Larger file size, potentially impacting load times
- Less frequently updated, with fewer recent commits
- More complex API, which may be overkill for simple use cases
Code Comparison
Keymaster:
key('⌘+r, ctrl+r', function() {
alert('refreshing page');
});
Keypress:
var listener = new window.keypress.Listener();
listener.sequence_combo("up up down down left right left right b a enter", function() {
alert("Konami code!");
});
Both libraries allow for binding key combinations, but Keypress offers more advanced features like sequence detection. Keymaster's syntax is more concise for simple bindings, while Keypress provides more flexibility for complex scenarios.
Keymaster is lightweight and straightforward, making it ideal for basic keyboard shortcuts. Keypress, on the other hand, offers a richer set of features for handling complex key interactions, but at the cost of a larger codebase and potentially steeper learning curve.
A tiny (~650 B) & modern library for keybindings.
Pros of tinykeys
- Significantly smaller bundle size (less than 1KB gzipped)
- Modern JavaScript with ES modules support
- Simpler API with a more focused feature set
Cons of tinykeys
- Less extensive browser support compared to keymaster
- Fewer advanced features (e.g., no key sequences or scopes)
- Smaller community and ecosystem
Code Comparison
keymaster:
key('⌘+R, ctrl+R', function() {
alert('stopped reload!');
return false;
});
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Control+r": (event) => {
event.preventDefault();
alert('stopped reload!');
},
});
Summary
tinykeys offers a more modern and lightweight approach to keyboard shortcuts, ideal for projects prioritizing small bundle sizes and ES module support. However, keymaster provides broader browser compatibility and more advanced features, making it suitable for complex applications requiring extensive keyboard control. The choice between the two depends on specific project requirements and constraints.
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Pros of hotkeys-js
- More actively maintained with recent updates
- Supports a wider range of key combinations and modifiers
- Includes TypeScript definitions out of the box
Cons of hotkeys-js
- Slightly larger file size compared to keymaster
- May have a steeper learning curve for beginners due to more features
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;
}
});
keymaster:
key('ctrl+a, ctrl+b, r, f', function(event, handler) {
if(handler.shortcut === 'ctrl+a') alert('you pressed ctrl+a!');
if(handler.shortcut === 'ctrl+b') alert('you pressed ctrl+b!');
if(handler.shortcut === 'r') alert('you pressed r!');
if(handler.shortcut === 'f') alert('you pressed f!');
});
Both libraries offer similar functionality for handling keyboard shortcuts, but hotkeys-js provides a more structured approach with its switch statement, while keymaster uses individual if statements for each shortcut.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
Pros of KeyboardJS
- More extensive and flexible API for complex key combinations
- Better support for international keyboard layouts
- Active development and maintenance
Cons of KeyboardJS
- Larger file size and potentially higher overhead
- Steeper learning curve for basic usage
Code Comparison
KeyboardJS:
KeyboardJS.bind('ctrl + shift + a', function(e) {
console.log('Ctrl+Shift+A pressed');
}, function(e) {
console.log('Ctrl+Shift+A released');
});
Keymaster:
key('ctrl+shift+a', function() {
console.log('Ctrl+Shift+A pressed');
});
Key Differences
- KeyboardJS offers separate callbacks for key press and release events
- Keymaster has a simpler syntax for basic key bindings
- KeyboardJS provides more granular control over key combinations
Use Cases
- KeyboardJS: Complex applications with advanced keyboard shortcuts
- Keymaster: Simpler projects requiring basic keyboard event handling
Community and Support
- KeyboardJS: Larger community, more frequent updates
- Keymaster: Established project with stable codebase
Performance
- KeyboardJS: May have slightly higher overhead due to additional features
- Keymaster: Lightweight and efficient for basic keyboard handling
Compatibility
- KeyboardJS: Better cross-browser compatibility and support for various keyboard layouts
- Keymaster: Good compatibility but may have limitations with certain keyboard configurations
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
Pros of jquery.hotkeys
- Integrates seamlessly with jQuery, making it easy to use in jQuery-based projects
- Supports a wider range of special keys and modifiers
- Allows for more granular control over event handling
Cons of jquery.hotkeys
- Requires jQuery as a dependency, which may not be ideal for all projects
- Less actively maintained compared to keymaster
- Limited support for complex key combinations
Code Comparison
keymaster:
key('⌘+r, ctrl+r', function() {
alert('refreshing page');
});
jquery.hotkeys:
$(document).bind('keydown', 'ctrl+r', function() {
alert('refreshing page');
});
Both libraries provide similar functionality for binding key events, but keymaster offers a more concise syntax. jquery.hotkeys relies on jQuery's event binding mechanism, while keymaster is a standalone library with its own API.
keymaster supports chaining multiple key combinations in a single binding, whereas jquery.hotkeys requires separate bindings for each combination. However, jquery.hotkeys provides more flexibility in terms of event types (keydown, keyup, keypress) and selector targeting.
Overall, keymaster is more lightweight and easier to use in non-jQuery projects, while jquery.hotkeys offers tighter integration with jQuery and more advanced features for jQuery-based applications.
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
keymaster.js
Keymaster is a simple micro-library for defining and dispatching keyboard shortcuts in web applications.
It has no dependencies.
Itâs a work in progress (e.g. beta), so spare me your nerdrage and instead contribute! Patches are welcome, but they are not guaranteed to make it in.
Usage
Include keymaster.js
in your web app*, by loading it as usual:
<script src="keymaster.js"></script>
Keymaster has no dependencies and can be used completely standalone. It should not interfere with any JavaScript libraries or frameworks.
*Preferably use a minified version that fits your workflow. You can
run make
to have UglifyJS (if you have it installed) create a
keymaster.min.js
file for you.
Defining shortcuts
One global method is exposed, key
which defines shortcuts when
called directly.
// define short of 'a'
key('a', function(){ alert('you pressed a!') });
// returning false stops the event and prevents default browser events
key('ctrl+r', function(){ alert('stopped reload!'); return false });
// multiple shortcuts that do the same thing
key('â+r, ctrl+r', function(){ });
The handler method is called with two arguments set, the keydown event
fired, and
an object containing, among others, the following two properties:
shortcut
: a string that contains the shortcut used, e.g. ctrl+r
scope
: a string describing the scope (or all
)
key('â+r, ctrl+r', function(event, handler){
console.log(handler.shortcut, handler.scope);
});
// "ctrl+r", "all"
Supported keys
Keymaster 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
and f1
through f19
.
Modifier key queries
At any point in time (even in code other than key shortcut handlers),
you can query the key
object for the state of any keys. This
allows easy implementation of things like shift+click handlers. For example,
key.shift
is true
if the shift key is currently pressed.
if(key.shift) alert('shift is pressed, OMGZ!');
Other key queries
At any point in time (even in code other than key shortcut handlers),
you can query the key
object for the state of any key. This
is very helpful for game development using a game loop. For example,
key.isPressed(77)
is true
if the M key is currently pressed.
if(key.isPressed("M")) alert('M key is pressed, can ya believe it!?');
if(key.isPressed(77)) alert('M key is pressed, can ya believe it!?');
You can also get these as an array using...
key.getPressedKeyCodes() // returns an array of key codes currently pressed
Scopes
If you want to reuse the same shortcut for separate areas in your single page app,
Keymaster supports switching between scopes. Use the key.setScope
method to set scope.
// define shortcuts with a scope
key('o, enter', 'issues', function(){ /* do something */ });
key('o, enter', 'files', function(){ /* do something else */ });
// set the scope (only 'all' and 'issues' shortcuts will be honored)
key.setScope('issues'); // default scope is 'all'
// remove all events that are set in 'issues' scope
key.deleteScope('issues');
Filter key presses
By default, when an INPUT
, SELECT
or TEXTAREA
element is focused, Keymaster doesn't process any shortcuts.
You can change this by overwriting key.filter
with a new function. This function is called before
Keymaster processes shortcuts, with the keydown event as argument.
If your function returns false, then the no shortcuts will be processed.
Here's the default implementation for reference:
function filter(event){
var tagName = (event.target || event.srcElement).tagName;
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
If you only want some shortcuts to work while in an input element, you can change the scope in the
key.filter
function. Here's an example implementation, setting the scope to either 'input'
or 'other'
.
Don't forget to return true
so the any shortcuts get processed.
key.filter = function(event){
var tagName = (event.target || event.srcElement).tagName;
key.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
return true;
}
However a more robust way to handle this is to use proper focus and blur event handlers on your input element, and change scopes there as you see fit.
noConflict mode
You can call key.noConflict
to remove the key
function from global scope and restore whatever key
was defined to before Keymaster was loaded. Calling key.noConflict
will return the Keymaster key
function.
var k = key.noConflict();
k('a', function() { /* ... */ });
key()
// --> TypeError: 'undefined' is not a function
Unbinding shortcuts
Similar to defining shortcuts, they can be unbound using key.unbind
.
// unbind 'a' handler
key.unbind('a');
// unbind a key only for a single scope
// when no scope is specified it defaults to the current scope (key.getScope())
key.unbind('o, enter', 'issues');
key.unbind('o, enter', 'files');
Notes
Keymaster should work with any browser that fires keyup
and keydown
events,
and is tested with IE (6+), Safari, Firefox and Chrome.
See http://madrobby.github.com/keymaster/ for a live demo.
CoffeeScript
If you're using CoffeeScript, configuring key shortcuts couldn't be simpler:
key 'a', -> alert('you pressed a!')
key 'â+r, ctrl+r', ->
alert 'stopped reload!'
off
key 'o, enter', 'issues', ->
whatevs()
alert 'shift is pressed, OMGZ!' if key.shift
Contributing
To contribute, please fork Keymaster, add your patch and tests for it (in the test/
folder) and
submit a pull request.
TODOs
- Finish test suite
Keymaster is (c) 2011-2013 Thomas Fuchs and may be freely distributed under the MIT license.
See the MIT-LICENSE
file.
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 robust Javascript library for capturing keyboard input. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
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