Create Keyboard Shortcuts for Web Apps with JavaScript | WebReference | 2 | WebReference

Create Keyboard Shortcuts for Web Apps with JavaScript | WebReference | 2


How Keyboard Shortcuts Work in Web Apps

In very plain words, all this library does is call your function when the specific keyboard combination is pressed. There are a few options that you can specify but we will discuss them later. You can download the shortcut .js file here.

This library offers two functions: add and remove.

Add a Shortcut

The add method accepts two or three parameters. The first one is the shortcut key combination, which should be specified in the following format: Modifier[+Modifier..]+Key.

The second parameter is the function to be called when the shortcut is triggered. The event variable is passed to it.

The third parameter, which is optional, is an associative array of options (more on this later).

Example Code


When you add a shortcut, you can specify five options:

  • type: string
    The event type that triggers the function. Values: 'keydown','keyup','keypress'. Default: 'keydown'.
  • disable_in_input: boolean
    If this is set to true, the function will not be called when the focus is on an input field or a textarea. This is very useful for single key shortcuts. Default: false.
  • target: DOM Element
    The element that should be watched for the keyboard event. Default: document.
  • propagate: boolean
    After the shortcut is captured, should the event propagate? Default: false.
  • keycode: integer
    Watch for this keycode. For example, the keycode '65' is 'a'.

Remove Shortcut

Usually you won't need to bother with removing a shortcut. However, under some circumstances, you need to remove it. And when you do, it is extremely simple to do so. Just call remove() with the key combination as its only parameter (For example: shortcut.remove("Ctrl+B");).

Supported Keys

This library supports most of the keys that come on standard keyboards. It also includes the Command key on a Macintosh keyboard. There are a few keys that are referred to as modifier keys. They can be combined with other keys to provide a shortcut. Here are the valid modifier keys:

  • Ctrl
  • Alt
  • Shift
  • Meta (Command key on Macintosh keyboards)

Other than the modifier keys, here are the keys that are supported by the library:

  • all alpha-numeric keys (a - z and 0 - 9)
  • Tab
  • Space
  • Return
  • Enter
  • Backspace
  • Scroll_lock
  • Caps_lock
  • Num_lock
  • Pause
  • Insert
  • Home
  • Delete
  • End
  • Page_up
  • Page_down
  • Left
  • Up
  • Right
  • Down
  • F1 - F12