Add Custom Keyboard Shortcuts to Your Site with Hotkey.js

Category: Javascript | March 10, 2025
Author:rameel
Views Total:79 views
Official Page:Go to website
Last Update:March 10, 2025
License:MIT

Preview:

Add Custom Keyboard Shortcuts to Your Site with Hotkey.js

Description:

Hotkey is a tiny (less than 1kb gzipped) JavaScript library for handling keyboard shortcuts and hotkeys in your web applications.

You can use this library to listen for key combinations like Ctrl+K on the window, document, or specific DOM elements to trigger custom logic.

How to use it:

1. Install the package and import the Hotkey.js library as follows:

# NPM
$ npm install @ramstack/hotkey
<script type="module">
  import { registerHotkey } from "https://cdn.jsdelivr.net/npm/@ramstack/hotkey@1/dist/hotkey.esm.min.js";
</script>
// OR
<script src="https://cdn.jsdelivr.net/npm/@ramstack/hotkey@1/dist/hotkey.min.js"></script>

2. The library provides a simple registerHotkey method to set up hotkey bindings on page elements. You can find all standard key names on Key values for keyboard events.

registerHotkey("#app", "Ctrl + K", e => {
  // do something
});
registerHotkey(document, "Ctrl + K", e => {
  // enable the hotkey on the whole document
});

3. Specify the event to trigger the key bindings. Default: ‘keydown’.

registerHotkey("#app", "Ctrl + K", e => {
  // do something
}, "keyup");

4. Ensure that only events marked as trusted are handled. This can help prevent synthetic or untrusted events from triggering hotkeys.

registerHotkey("#app", "Ctrl + K", e => {
  // do something
}, "keyup", {
  trusted: true
});

5. Prevent hotkey handling on certain elements using the data-hotkey-ignore attribute:

<input type="text" data-hotkey-ignore>

Changelog:

v1.1.0 (03/10/2025)

  • Add trusted option

You Might Be Interested In:


Leave a Reply