JAVA SCRIPT - Handling Keyboard Shortcuts with Mousetrap

Handling Keyboard Shortcuts with Mousetrap

Problem

You need to provide support for keyboard shortcuts, but coding for these is exceedingly
tedious.

Solution

Use a standalone library, such as Keypress, or a jQuery plugin, like jQuery.hotkeys.
Keypress is very simple to use. Just drop in the library, and set up the shortcuts or key
combinations you want to capture. You can capture simple combos, or more complex
sequences:

EXPLAIN

Capturing keystrokes and shortcut combinations isn’t a complex task, but it is tedious,
which makes it ideal for a library.
Two popular libraries for keyboard shortcut and key tracking are Mousetrap and the
one demonstrated in the solution, Keypress.

I went with Keypress because it looks to be
more actively maintained than Mousetrap—an important consideration when picking
a library. In addition, Keypress supports more sophisticated keyboard actions I found
to be useful.
Keypress is very easy to use, as the solution demonstrated.

There are three simple meth‐
ods to use:

• simple_combo: For the typical two-key shortcut, such as Ctrl+a

• counting_combo: Takes two arguments, the key sequence, and a counter

• sequence_combo: Takes a sequence of keys
The counting_combo() function is a handy bit of code.

It takes a two-key combination,
such as Tab+space, or Ctrl+a. As long as you continue holding down the first key, the
counter increases for key press on the second key. It makes a great way to cycle through
tabs, or highlight paragraphs in a row, or whatever action cycling through a collection.

Any key combination can be a modifier in Keypress. Typically, modifiers would be
combinations like Alt+q, Ctrl+a, or Shift+r. The combinations begin with one of the
three:

• Ctrl

• Shift

• Tab

Keypress basically allows you to define your shortcut to be whatever you want it to be,
which is extensible, but use such freedom with caution: we’re creatures of habit, and we
like our shortcuts to be familiar.

If you need something even more complicated, there’s register_combo() that takes an
object specifying any number of properties associated with the key action. In the fol‐
lowing code, register_combo() specifies both key up and key down functions, as well
as setting the is_unordered to true. This property allows me to type Alt+m and m+Alt,
equally:

There are also opportunities to pause the keyboard capturing when the cursor is in an
input field or in other circumstances. Keypress works equally on its own or in combi‐
nation with JQuery.
If you prefer to use a jQuery plugin, though, then jQuery.hotkeys is probably for you,
as demonstrated in the solution.

Note, though, that its functionality is limited compared
to Keypress. However, if you’re only interested in creating traditional shortcuts, then
the plugin fits your needs.
To use, simply map the key combination using jQuery’s on()/off() syntax, or you can
use the plugins own bind()/unbind() methods.