Bind Keyboard Shortcuts To Custom Actions – Keywatch

Category: Javascript | February 27, 2021
Views Total:75 views
Official Page:Go to website
Last Update:February 27, 2021


Bind Keyboard Shortcuts To Custom Actions – Keywatch


Keywatch is a JavaScript library that makes it easier to assign keyboard shortcuts to any actions you like.

Supports single keys, modifiers (Shift, Alt, Control or Meta), and even key sequences (e.g. Konami cheat code).

It also provides a Keywatch Viewer where you can view key bindings as well as check whether the binding works in your current browser.

How to use it:

1. Install & download.

# Yarn
$ yarn add keywatch
$ npm i keywatch
2. Import the Keywatch as a module.
import { watch } from 'keywatch';

3. Bind a handler function to a single key.'Enter', () => {
  console.log('Pressed Enter')

4. We can specify keyboard modifiers to further adjust if we only want to listen to key combinations. These are ShiftAltControl and Meta. The latter is Command on Macs and Win on Windows. Each of them has a us-ascii short representation: +#^@, and even accept the usual mac-keys ⇧⌥⌘.

// Shift
watch("Shift KeyA", action)
watch("+a", action)
watch("⇧a", action)
// Alt
watch("Alt KeyS", action)
watch("#s", action)
watch("⌥s", action)
// Control
watch("Control KeyD", action)
watch("ctrl d", action)
watch("^d", action)
// Win
watch("Meta KeyF", action)
watch("@f", action)
watch("⌘f", action)

5. You may have noticed, that Control-D or Win-F may have triggered a default browser action. In order to prevent these we have to prefix the key definition with a NoDefault (short !).

// Control-D
watch("NoDefault Control KeyD", action)
watch("!^d", action)
// Win-F
watch("NoDefault Win KeyF", action)
watch("!@f", action)

6. You can also use more than one Modifier for a Key. Just keep in mind that the key definition is always exact. This means that Shift KeyA will not trigger on Shift Alt KeyA.

// Shift-E
watch("Shift KeyE", action)
watch("+KeyE", action)
// Shift-Alt-E
watch("Shift Alt KeyE", action)
watch("+#KeyE", action)
// Shift-Control-E
watch("Shift Control KeyE", action)
watch("+^KeyE", action)

You Might Be Interested In:

Leave a Reply