Top Related Projects
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
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
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript applications. It allows developers to easily add and manage keyboard events without worrying about cross-browser inconsistencies or complex key combinations.
Pros
- Lightweight and easy to use
- Supports complex key combinations and sequences
- Works across different browsers and platforms
- No external dependencies
Cons
- Limited to keyboard events only
- May conflict with native browser shortcuts if not carefully implemented
- Doesn't handle non-US keyboard layouts natively
- Lacks advanced features like customizable key repeat rates
Code Examples
Basic key binding:
Mousetrap.bind('ctrl+s', function(e) {
e.preventDefault();
console.log('Ctrl+S was pressed');
});
Binding a sequence of keys:
Mousetrap.bind('up up down down left right left right b a enter', function() {
console.log('Konami code activated!');
});
Binding to multiple keys:
Mousetrap.bind(['command+k', 'ctrl+k'], function(e) {
console.log('Command+K or Ctrl+K was pressed');
return false;
});
Getting Started
- Include Mousetrap in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.6.5/mousetrap.min.js"></script>
- Start binding keyboard shortcuts:
// Single key
Mousetrap.bind('4', function() { console.log('4 pressed'); });
// Combinations
Mousetrap.bind('command+shift+k', function() { console.log('Command+Shift+K pressed'); });
// Sequences
Mousetrap.bind('g i', function() { console.log('Go to inbox'); });
// Map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], function() {
console.log('Command+K or Ctrl+K pressed');
return false;
});
Competitor Comparisons
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
Pros of Keymaster
- Smaller file size (about 1.4KB minified and gzipped)
- Supports key sequences and key combinations
- Built-in support for modifier keys (shift, ctrl, alt, option, meta, command)
Cons of Keymaster
- Less actively maintained (last update in 2016)
- Fewer features compared to Mousetrap
- Limited browser compatibility information
Code Comparison
Keymaster:
key('⌘+r, ctrl+r', function() {
alert('stopped reload!');
return false;
});
Mousetrap:
Mousetrap.bind(['command+r', 'ctrl+r'], function(e) {
alert('stopped reload!');
return false;
});
Both libraries offer similar syntax for binding key combinations, with Keymaster using a slightly more concise approach. Mousetrap provides more extensive documentation and examples, while Keymaster focuses on simplicity and lightweight implementation.
Keymaster is a good choice for projects requiring basic keyboard shortcut functionality with a minimal footprint. Mousetrap offers more features and active development, making it suitable for larger applications or those needing advanced key binding capabilities.
A keyboard input capturing utility in which any key can be a modifier key.
Pros of Keypress
- More flexible key combination handling, allowing for complex sequences
- Supports key recording and playback functionality
- Smaller file size, potentially leading to faster load times
Cons of Keypress
- Less actively maintained, with fewer recent updates
- More limited browser compatibility compared to Mousetrap
- Lacks some advanced features like global binding and unbinding
Code Comparison
Keypress:
var listener = new window.keypress.Listener();
listener.simple_combo("shift s", function() {
console.log("You pressed shift and s");
});
Mousetrap:
Mousetrap.bind("shift+s", function() {
console.log("You pressed shift and s");
});
Both libraries offer straightforward ways to bind key combinations, but Keypress uses a more object-oriented approach with its Listener
class. Mousetrap's syntax is slightly more concise and may be easier for beginners to understand.
While Keypress provides more flexibility for complex key sequences, Mousetrap offers broader browser support and more active maintenance. The choice between the two depends on specific project requirements, such as the need for advanced key combination handling versus wider compatibility and ongoing updates.
A tiny (~650 B) & modern library for keybindings.
Pros of tinykeys
- Smaller bundle size (1.5KB vs 5.2KB for Mousetrap)
- Modern JavaScript with TypeScript support
- Simpler API with a more declarative approach
Cons of tinykeys
- Less extensive browser support compared to Mousetrap
- Fewer features and customization options
- Smaller community and ecosystem
Code Comparison
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Shift+D": () => {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
},
});
Mousetrap:
import Mousetrap from "mousetrap";
Mousetrap.bind("shift+d", function() {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
});
Both libraries provide similar functionality for handling keyboard shortcuts, but tinykeys uses a more modern and concise syntax. Mousetrap offers more flexibility and options, while tinykeys focuses on simplicity and a smaller footprint. The choice between the two depends on project requirements, browser support needs, and personal preference for API style.
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Pros of hotkeys-js
- Supports a wider range of key combinations, including modifier keys
- Provides more flexible binding options, such as scoping to specific elements
- Offers better performance for complex key combinations
Cons of hotkeys-js
- Less extensive documentation compared to Mousetrap
- Smaller community and fewer contributors
- May have a steeper learning curve for beginners
Code Comparison
Mousetrap:
Mousetrap.bind('ctrl+shift+k', function() {
console.log('Ctrl+Shift+K pressed');
});
hotkeys-js:
hotkeys('ctrl+shift+k', function(event, handler) {
console.log('Ctrl+Shift+K pressed');
});
Both libraries offer similar syntax for basic key bindings, but hotkeys-js provides more advanced features for complex scenarios:
hotkeys('ctrl+shift+k', {scope: 'editor'}, function(event, handler) {
console.log('Ctrl+Shift+K pressed in editor scope');
});
Overall, hotkeys-js offers more flexibility and advanced features, while Mousetrap provides a simpler API with better documentation. The choice between the two depends on the specific requirements of your project and your familiarity with keyboard event handling.
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
- Active development and maintenance
Cons of KeyboardJS
- Slightly larger file size
- May have a steeper learning curve due to more complex API
Code Comparison
Mousetrap:
Mousetrap.bind('ctrl+s', function(e) {
e.preventDefault();
// Save functionality
});
KeyboardJS:
KeyboardJS.bind('ctrl + s', function(e) {
e.preventDefault();
// Save functionality
});
The basic usage for binding keyboard shortcuts is similar between the two libraries. However, KeyboardJS offers more advanced features for complex key combinations and sequences:
KeyboardJS.bind('ctrl + alt + del -> ctrl + alt + insert', function(e) {
console.log('Complex key sequence detected');
});
Both libraries provide simple and effective ways to handle keyboard events in web applications. Mousetrap is lighter and easier to use for basic needs, while KeyboardJS offers more advanced features and better international keyboard support. The choice between them depends on the specific requirements of your project and the level of keyboard interaction complexity you need to handle.
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
Pros of jquery.hotkeys
- Lightweight and simple to use
- Integrates seamlessly with jQuery
- Supports special keys and key combinations
Cons of jquery.hotkeys
- Requires jQuery as a dependency
- Less actively maintained (last update in 2015)
- Limited functionality compared to more modern libraries
Code Comparison
jquery.hotkeys:
$(document).bind('keydown', 'ctrl+a', function() {
alert('You pressed CTRL + A');
});
Mousetrap:
Mousetrap.bind('ctrl+a', function() {
alert('You pressed CTRL + A');
});
Key Differences
- Dependency: jquery.hotkeys requires jQuery, while Mousetrap is standalone.
- Maintenance: Mousetrap is more actively maintained and updated.
- Features: Mousetrap offers more advanced features like sequence detection and pause/unpause.
- Browser Support: Mousetrap has broader browser compatibility.
- Community: Mousetrap has a larger user base and more GitHub stars.
Conclusion
While jquery.hotkeys is a simple and effective solution for jQuery-based projects, Mousetrap offers a more robust, actively maintained, and feature-rich alternative for keyboard event handling. Mousetrap's independence from jQuery and broader browser support make it a more versatile choice for modern web 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
Mousetrap
Mousetrap is a simple library for handling keyboard shortcuts in Javascript.
It is licensed under the Apache 2.0 license.
It is around 2kb minified and gzipped and 4.5kb minified, has no external dependencies, and has been tested in the following browsers:
- Internet Explorer 6+
- Safari
- Firefox
- Chrome
It has support for keypress
, keydown
, and keyup
events on specific keys, keyboard combinations, or key sequences.
Getting started
-
Include mousetrap on your page before the closing
</body>
tag<script src="/path/to/mousetrap.min.js"></script>
or install
mousetrap
fromnpm
and require itvar Mousetrap = require('mousetrap');
-
Add some keyboard events to listen for
<script> // single keys Mousetrap.bind('4', function() { console.log('4'); }); Mousetrap.bind("?", function() { console.log('show shortcuts!'); }); Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup'); // combinations Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); }); // map multiple combinations to the same callback Mousetrap.bind(['command+k', 'ctrl+k'], function() { console.log('command k or control k'); // return false to prevent default browser behavior // and stop event from bubbling return false; }); // gmail style sequences Mousetrap.bind('g i', function() { console.log('go to inbox'); }); Mousetrap.bind('* a', function() { console.log('select all'); }); // konami code! Mousetrap.bind('up up down down left right left right b a enter', function() { console.log('konami code'); }); </script>
Why Mousetrap?
There are a number of other similar libraries out there so what makes this one different?
- There are no external dependencies, no framework is required
- You are not limited to
keydown
events (You can specifykeypress
,keydown
, orkeyup
or let Mousetrap choose for you). - You can bind key events directly to special keys such as
?
or*
without having to specifyshift+/
orshift+8
which are not consistent across all keyboards - It works with international keyboard layouts
- You can bind Gmail like key sequences in addition to regular keys and key combinations
- You can programatically trigger key events with the
trigger()
method - It works with the numeric keypad on your keyboard
- The code is well documented/commented
Tests
Unit tests are run with mocha.
Running in browser
View it online to check your browser compatibility. You may also download the repo and open tests/mousetrap.html
in your browser.
Running with Node.js
-
Install development dependencies
cd /path/to/repo npm install
-
Run tests
npm test
Documentation
Full documentation can be found at https://craig.is/killing/mice
Top Related Projects
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
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