Javascript: Mousetrap.js

Mousetrap is a small standalone library with no external dependency.
It is used for handling keyboard events, shortcuts in the browser.
Mostly when building complex UI's, it is helpful or necessary to provide the user with keyboards shortcuts.
This is also conceivable in video games or something like that.

Let's look at the example:
Bind a single Key:
Mousetrap.bind(‘4’, function() {
  console.log(‘you pressed 4’)

Note: It makes a difference whether it is a capital or small letter that was defined or pressed. For Mousetrap, for example, x is not equal to X.
Bind a single key, trigger the function when you let the key come up, after holding it down.

Mousetrap.bind(‘x’, function() {
  console.log(‘You pressed x and let it come up’)

Trigger when the a, b & c keys are pressed in sequence. The specified sequence must be observed.

Mousetrap.bind(‘a b c’, function() {
  console.log(‘You pressed a, then b & after that you pressed c’)

Creating a key combination:
Mousetrap.bind(‘command+shift+k’, function(e) {
  console.log(‘you pressed command, shift & k’)

Several key combinations, which should be reacted to in the same way, can be passed with an array:
Mousetrap.bind([‘a+d’, ‘w+s’], function(e) {
  console.log(‘you pressed a & d OR w & s’)

JSfiddle link:
CDN link:

npm install mousetrap
import Mousetrap from ‘mousetrap’

For more, check out the official documentation.

I hope it was helpful.
For more such articles please subscribe.

Written By:
Saurabh Joshi 


Popular Posts