Mousetrap - Keyboard shortcuts in Javascript

1,749 阅读2分钟
原文链接: craig.is
// single keys
Mousetrap.bind('4', function() { highlight(2); });
Mousetrap.bind("$", function() { highlight(3); }, 'keydown');
Mousetrap.bind('x', function() { highlight(4); }, 'keyup');

// combinations
Mousetrap.bind('command+shift+K', function() { highlight(7); });
Mousetrap.bind(['command+k', 'ctrl+k'], function() { highlight(8); });

// gmail style sequences
Mousetrap.bind('g i', function() { highlight(11); });
Mousetrap.bind('* a', function() { highlight(12)});

// konami code!
Mousetrap.bind('up up down down left right left right b a enter', function() {
    highlight([15, 16, 17]);
});

Introduction

Mousetrap is a standalone library with no external dependencies. It weighs in at around 1.4kb minified and gzipped.

What are you waiting for? Throw away your mouse and download it now.

Browser Support

Mousetrap has been tested and should work in

  • Internet Explorer 6+
  • Safari
  • Firefox
  • Chrome

Supported Keys

For modifier keys you can use shift, ctrl, alt, option, meta, and command.

Other special keys are backspace, tab, enter, return, capslock, esc, escape, space, pageup, pagedown, end, home, left, up, right, down, and del.

Any other key you should be able to reference by name like a, /, $, *, or =.

API Reference

I. Mousetrap.bind

The bind method is the main call you will be making. This will bind a specified keyboard command to a callback method.

Single key

Mousetrap.bind('/', _focusSearch);

There is a third argument you can use to specify the type of event to listen for. It can be keydown or keyup and defaults to keydown.

Combination of keys

Mousetrap.bind('ctrl+s', function(e) {
    _saveDraft();
});

The callback function you specify receives a single argument with the key event that triggered the callback. From here you can decide if you want to prevent the default behavior or stop propogation or what not.

If you want to bind multiple key commands to the same callback you can pass in an array for the first argument (a comma separated list should also work):

Mousetrap.bind(['ctrl+s', 'command+s'], function(e) {
    _saveDraft();
});

Note that modifier keys are not explicitly tracked but rather are referenced using e.shiftKey, e.metaKey, e.ctrlKey, and e.altKey.

This is more reliable than tracking because if you are holding one of the modifier keys down when you focus the window the browser won't get a keydown event for that key.

Sequence of keys

Mousetrap.bind('* a', _selectAll, 'keydown');

This feature was inspired by Gmail. Any keys separated by a space will be considered a sequence. If you type each key in order the final one in the sequence will trigger the callback. If you type a key not in the sequence or wait too long the sequence will reset.

You can also make a sequence that includes key combinations within it.

Mousetrap.bind('g o command+enter', function() { /* do something */ });

Any key events that would normally fire for keys within a sequence will not fire if they are pressed within the context of that sequence.

For example if you have a keydown listener for the o key and you press o as part of the sequence above, the event for o on its own will not fire. As soon as the sequence is broken it will fire again.

It is important to note that Mousetrap can get very confused if you have a single key handler that uses the same key that a sequence starts with. This is because it can't tell if you are starting the sequence or if you are pressing that key on its own.

Shift key

Mousetrap.bind('?', function() { alert('keyboard shortcuts'); });

Keys that require shift are handled magically for you. They should just work out of the box. Saying ? is the same thing as saying shift+/.

Text fields

By default all keyboard events will not fire if you are inside of a textarea, input, or select to prevent undesirable things from happening.

If for whatever reason you want them to you can add the class mousetrap to the element.

Binding again

If you bind the same key event later on in your script it should overwrite the original callback you had specified.

II. Mousetrap.trigger

Mousetrap.trigger('esc');

Any keyboard event that has been bound can be triggered by passing in the string you used when you bound it originally.

Note that this is not actually triggering a key event in the browser. It is simply firing the event you bound to that key within mousetrap

III. Mousetrap.reset

Mousetrap.reset();

The reset method will remove anything you have bound to mousetrap. This can be useful if you want to change contexts in your application without refreshing the page in your browser. You can ajax in a new page, call reset, and then bind the key events needed for that page.

Internally mousetrap keeps an associative array of all the events to listen for so reset does not actually remove or add event listeners on the document. It just sets the array to be empty.

IV. Mousetrap.init

Mousetrap.init();

Init is called onload for the page where you have included mousetrap.js. All it does is setup global listeners on document to handle within mousetrap and delegate appropriate events based on mousetrap key bindings.

You shouldn't need to call init manually, and if you did it could probably cause double events firing.

Support and Bugs

If you are having trouble, have found a bug, or want to contribute don't be shy.
Open a ticket on Github.