Handle Keyboard Shortcuts With Mousetrap.js

Mousetrap

Mousetrap.js is a javascript plugin that makes it easy to setup keyboard shortcuts for your web applications.

It allows you to define functions to run on certain key pushes, you can set it on a single key or a combination of keys together or a sequence of keys.

Mousetrap.js is available on github and you can download it here.

Download Mousetrap.js

Browser Support

Mousetrap.js can be used in any browser, it has support built in to be used on:

  • Internet Explorer 6+
  • Chrome
  • Safari
  • Firefox
  • Opera

How To Use

Just like any other Javascript file all you have to do is include it on the page and a new mousetrap object will be created for you.

<script src="./js/mousetrap.js"></script>


Including the mousetrap.js file on the page will create a new Javascript object called Mousetrap you will use to apply the keyboard shortcuts.

To use the Mousetrap object all you have to do is use the following code.

<script>
Mousetrap.bind(key, function(e) {
     // functionality of key button 		
});
</script>

Single Key

To define a single key to use with the mousetrap you will use the following code.

Mousetrap.bind('/', function(e) {
    // functionality to run on when pushed the / button.
});

Combination Of Keys

If you want to define a combination of keys, such as ctrl+s to save or ctrl+c to copy, you can do so with mousetrap.js.

Mousetrap.bind('ctrl+s', function(e) {
    // functionality to run on the ctrl+s
});

If you want to use two different combination of keys to perform the same functionality you do this by separating them with a comma.

/**
 * Save the document for both windows and mac users
 */
Mousetrap.bind(['ctrl+s', 'command+s'], function(e) {
     // Save the document
});

Sequence Of Keys

Along with a combination of keys you can create a sequence of keys which will run a certain function.

Any keys which are separated by a space will be treated as a sequence.

/**
 * Sequence of keys
 */
Mousetrap.bind(['q w e r t y'], function(e) {
     // functionality that will run when you type the word qwerty
});

View the demo to see they work.

Demo

Download

If you want to use mousetrap on your next web application you can download it from github.

Download Mousetrap.js

Advertise here

Comment