Keybinding documentation

Allows you to bind and unbind events to individual keypresses or sequences of keypresses. Intended for implementing keyboard shortcuts.

bind

bind(keyString, fn, options)

Binds a callback to a specified keypress.

Arguments

keyString

A string of the key or key combination or sequence to bind to. For a list of key values, see Key Values on MDN.

For each key binding, the user's keypresses will be recorded up to the length of the bound sequence. Once the event is fired, the logged keypresses are deleted.

Keypresses will never be recorded while keyboard focus is in a password input, and by default they will also not be recorded while keyboard focus is in any element that expects keyboard input.

Some key names also have aliases:

Space
'space' 'spacebar'
Up arrow
'up'
Right arrow
'right'
Down arrow
'down'
Left arrow
'left'
Escape
'esc'

Modifier keys cannot be detected directly, but can be combined with other keys using '+', e.g. 'ctrl+m'

Alt
'alt'
Control or Command
'control' 'ctrl' 'command' 'cmd' 'meta'
Shift
'shift'

Sequences of keys can be bound using keyStrings like 'ctrl+k ctrl+b'

fn

The function to bind to the keypress, using a keydown event.

options

An options object with any of these properties:

allowInInput boolean false
If set to true, the keypresses will be checked while the keyboard focus is in an element that accepts keyboard input, such as a text input or a textarea.

unbind

unbind(keyString, fn)

Unbinds a function from a specified key or set of keys.

Arguments

keyString

A string of the key or keys the event is bound to.

fn

The function to unbind to the keypress.

Examples

Try the following keyboard shortcuts/sequences:

  • a
  • Ctrl + m (will work while focus in input)
  • Konami code (up up down down left right left right b a enter)

Keyboard shortcuts won't fire when your focus is in an input, unless it's specified that it should.

Keep in mind that only some browser shortcuts (e.g. Ctrl + s) can have their default action prevented with event.preventDefault(). If you ever do this, be sure to test it in multiple browsers.