Add Custom Keyboard Shortcuts to Your Site with Hotkey.js

Category: Javascript | February 26, 2024
Author:rameel
Views Total:27 views
Official Page:Go to website
Last Update:February 26, 2024
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");

You Might Be Interested In:


Leave a Reply