Custom Keybinds and Hotkeys in JavaScript – Keybind.js

Category: Javascript | November 18, 2024
Authorbarleybobs
Last UpdateNovember 18, 2024
LicenseMIT
Views92 views
Custom Keybinds and Hotkeys in JavaScript – Keybind.js

Keybind.js is a lightweight (<1kb minified) JavaScript library that adds keyboard shortcut support to your web applications.

This keybinding library provides two binding types to match different keyboard shortcut needs.

Single-key bindings activate immediately upon key press, perfect for quick actions like toggling panels or triggering simple commands.

Multi-key bindings support combinations like Control+A or Control+Alt+Delete, which will activate when any key in the combination is released.

How to use it:

1. Download the Keybind.js library and include it on the webpage.

<script src="keybind.min.js"></script>

2. Initialize Keybind.js and create custom keybindings.

Note that the library uses standard JavaScript key codes, which can be found at MDN Web Docs.

// For single keybindings:
const keybind = new Keybind({
  name: 'MyKeybinding',
  type: 'single',
  codes: new Set(['KeyA'])
});
// For multi-key hotkeys:
const keybind = new Keybind({
  name: 'MyKeybinding',
  type: 'multi',
  codes: new Set(['ControlLeft', 'KeyB'])
});

3. React to key combinations by adding event listeners:

// Keybind activation:
document.addEventListener('keybindpress', function () {
  console.log('Key combination activated');
});
// Keybind detection:
document.addEventListener('keybindbound', function () {
  console.log('New key combination set');
});

4. Manually update keys for a keybinding:

keybind.set_manual(new Set(['ControlLeft', 'KeyB']));

5. Detect and enable user-defined key combinations:

keybind.set_detect();

You Might Be Interested In:


Leave a Reply