1

Handle Keyboard Shortcuts With Mousetrap.js

Mousetrap.js is a jquery 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.

The mousetrap.js jQuery plugin 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

To use Mousetrap.js all you have to do is use it just like any other jQuery plugin. First you need to include the latest version of jQuery.

With jQuery included on the document you can now include mousetrap.js.

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.


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

This article was originally published on Handle Keyboard Shortcuts With Mousetrap.js.


 

Leave a reply