Learn how to add keyboard shortcuts in Javascript using the Mousetrap Library.

The Right Way to add keyboard shortcuts in Javascript with Mousetrap

A person that doesn't like to waste time by pressing and selecting everything with the mouse is usually accustomed to use keyboard shortcuts to boost all his activities. If your application is widely used by this kind of person, you may probably already considered to implement shortcuts with JavaScript and if you're looking for this tutorial, you have maybe faced a bad time with the key press events on JavaScript:

document.onkeypress = function(e){
    displayunicode(e);
};

function displayunicode(e){
    var unicode = e.keyCode? e.keyCode : e.charCode;
    console.log(unicode);
}

At first glance, it doesn't look bad. However, if you want to do some action when a specific key is pressed, you will need to knew its code, besides if you want to handle combinations you will end up with more code (and including jQuery):

$(document).keydown(function(e){
    if( e.which === 89 && e.ctrlKey ){
        alert('control + y'); 
    }else if( e.which === 90 && e.ctrlKey ){
        alert('control + z'); 
    }          
});

That's why we recommend you, if you work with keyboard combinations, use MouseTrap and end up with your suffering. 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

Did I mention that it works on IE 6+ ? Nope ? Well, I will say it again, it works on IE 6+. It has support for keypress, keydown, and keyup events on specific keys, keyboard combinations, or key sequences. Unlike other libraries, mousetrap doesn't have any external dependency but only its code base.

1. Download and install Mousetrap

The source of MouseTrap is available on Github. If you use package managers, you can install it via NPM:

npm install mousetrap

Then you will be able to require it using var Mousetrap = require('mousetrap');. Alternatively you can download the distributable minified version here or the source code and then include it in your document using a script tag:

<!-- Reference mousetrap from a local file -->
<script src="mousetrap.min.js"></script>

<!-- Or using a CDN -->
<script src="https://cdn.rawgit.com/ccampbell/mousetrap/825ce50c/mousetrap.min.js"></script>

Once referenced, you will be able to access the library in the document with the global variable Mousetrap.

2. Adding shortcuts

To add keyboard shortcuts in your document, Mousetrap has the useful method bind. This method expects as first argument either a string or an array with some literal keyboard combinations. That's right ! You don't need to know with accuracy the codes of every key on your keyboard to add a couple of shortcuts in your app.

Single keys

As previously mentioned, you can add a shortcut for a single key by specifying its value on the first argument string of bind:

Mousetrap.bind('4', function() { 
    console.log('4'); 
});

Mousetrap.bind("?", function() { 
    console.log('show shortcuts!'); 
});

Change keyevent trigger

By default, Mousetrap action is triggered when the key is down (and if pressed continuously triggered). If you want to change this behaviour and trigger its callback only once when the key is up, you can specify it with the third argument of bind:

Mousetrap.bind('esc', function() { 
    console.log("You pressed escape, don't you try to run !"); 
// On keyup
}, 'keyup');

Special keys for combinations

With Mousetrap you are able to specify when a special key is pressed (CTRL on Windows, Command on Mac or the Alt key) and create a combination:

Mousetrap.bind('alt+a', function() { 
    alert("You pressed ALT+A !");
});

Mousetrap.bind('command+shift+k', function() {
    console.log('command shift k !'); 
});

Mousetrap.bind(['command+k', 'ctrl+k'], function() {
    console.log('command || ctrl k !'); 
});

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors