If our application is widely used by a person who doesn’t like to waste time by pressing and selecting everything with the mouse, then we should consider implementing shortcuts with JavaScript. A person who is usually accustomed to use keyboard shortcuts will certainly find it easy to boost all his activities.  Mousetrap is a simple library for handling keyboard shortcuts in JavaScript. It has support for keypress, keydown and keyup events on specific keys, keyboard combinations, or key sequences.

Why Mousetrap?

There are a number of other similar libraries out there but the following features makes this one different.

  • There are no external dependencies, no framework is required
  • It works with international keyboard layouts
  • You can bind Gmail like key sequences in addition to regular keys and key combinations
  • You can programmatically trigger key events with the trigger()method
  • It works with the numeric keypad on your keyboard
  • The code is well documented/commented

A sample application implemented in WaveMaker showcases the usage and easiness of using mousetrap plugin.

How to get started

Download the minified version and include it in your page using a script tag

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. Some examples are given below for various cases.

To add shortcut for a single key by specifying its value on the first argument string of bind:

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:

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:

With these properties checked, we will have a look at our application.

There are 2 forms in the main page.
Clicking on the first form should call the function to enable keyboard shortcut ctrl+s for saving using save button in that particular form.

Similarly, for second form, on clicking and then keyboard shortcut should enable save using second save button.


Lets have a look at the code.

On clicking on first form, setupVar1($event, $scope) is invoked and for second form,  setupVar2($event, $scope) is invoked respectively. In that we are binding Mousetrap property to add keyboard shortcut ‘command+s’ or ‘ctrl+s’ for each buttons. generateBtn() method is used to determine the save button.

Similarly, mousetrap has many other methods like unbind, trigger, stopCallback, reset etc which makes developers life easy!