npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ramstack/hotkey

v1.0.2

Published

A lightweight Javascript library for handling hotkeys. No external dependencies.

Downloads

7

Readme

Hotkey

The @ramstack/hotkey package is a very small and lightweight library for handling hotkeys. The library weighs around 1.32KB and approximately 750 bytes when gzipped.

Installation

Using via NPM

npm install --save @ramstack/hotkey

Using via CDN

<script src="https://cdn.jsdelivr.net/npm/@ramstack/hotkey@1/dist/hotkey.min.js"></script>

Using ES module build

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

Quick start

You can specify either the element itself or its selector as the target for key events. For global listening across the entire page, use window or document.

registerHotkey("#app", "Ctrl + K", e => {
  e.preventDefault();
  console.log("Search...");
});

The function returns a cleanup function that allows you to unsubscribe from event listening.

const cleanup = registerHotkey(...);
...

// Unregister the hotkey when they are no longer needed
cleanup();

Exclude elements from hotkey handling

If you wish to prevent hotkey handling on certain elements, add the data-hotkey-ignore attribute to the respective element.

<div id="app">
    ...
    <!-- Ignoring hotkeys on the input element -->
    <input type="text" data-hotkey-ignore>
</div>

Alternatively, apply it to the parent if you want to exclude an entire group of elements at once.

<div id="app">
    ...
    <!-- Ignoring hotkeys on form elements -->
    <form data-hotkey-ignore>
        ...
    </form>
</div>

API

/**
 * Registers a hotkey on the specified target element.
 *
 * @param {EventTarget | string} target - The target element on which the hotkey will be registered.
 * @param {string} hotkey - The combination of keys for the hotkey, e.g., "Ctrl+Alt+Delete".
 * @param {(e: KeyboardEvent) => void} handler - The function to be called when the hotkey is triggered.
 * @param {string} [eventName="keydown"] - The name of the event to listen for (default is "keydown").
 * @param {AddEventListenerOptions | boolean | undefined} [options] - Additional options for the event listener.
 *
 * @returns {() => void} - A function to unregister the hotkey.
 */
function registerHotkey(
    target: EventTarget | string,
    hotkey: string,
    handler: (e: KeyboardEvent) => void,
    eventName?: string,
    options?: AddEventListenerOptions | boolean | undefined): () => void;

Parameters

target (required)

The target element on which the hotkey will be registered. Use window or document for global hotkeys.

registerHotkey(window, "Win + PgUp", e => {
    console.log("Do something");
});

hotkey (required)

The combination of keys for the hotkey, e.g., Ctrl + Alt + Delete The hotkey description is a case-insensitive. Spaces are not important. Standard key names are used. You can find them here Key values for keyboard events

In addition, there are also aliases for some key names:

const aliases: Record<string, string> = {
    "esc"         : "escape",
    "ins"         : "insert",
    "del"         : "delete",
    "up"          : "arrowup",
    "down"        : "arrowdown",
    "right"       : "arrowright",
    "left"        : "arrowleft",
    "pgup"        : "pageup",
    "pgdn"        : "pagedown",
    "break"       : "pause",
    "scroll"      : "scrolllock",
    "scrlk"       : "scrolllock",
    "prtscr"      : "printscreen",
    "win"         : "meta",
    "windows"     : "meta",
    "cmd"         : "meta",
    "command"     : "meta",
    "comma"       : ",",
    "period"      : ".",
    "quote"       : "\"",
    "singlequote" : "'",
    "colon"       : ":",
    "semicolon"   : ";",
    "plus"        : "+",
    "minus"       : "-",
    "tilde"       : "~",
    "equal"       : "=",
    "slash"       : "/"
};

handler (required)

The function to be called when the hotkey is triggered.

The value of this inside the handler will be a reference to the element. It will be the same as the value of the currentTarget property of the event argument that is passed to the handler.

registerHotkey("#el", "Ctrl + K", function(e) {
    console.log(e.currentTarget === this); // logs true
});

As a reminder, arrow functions do not have their own this context.

registerHotkey("#el", "Ctrl + K", e => {
    console.log(e.currentTarget === this); // logs false
});

eventName (optional, default: 'keydown')

The name of the event to listen for. You can subscribe to events on keydown (used by default) or keyup.

registerHotkey(window, "Ctrl + Up", e => {
    e.preventDefault();
    ...
}, "keyup");

options (optional)

Additional options for the event listener. See Options.

Returns

A function that, when called, unregisters the hotkey.

const cleanup = registerHotkey(...);
...

// Unregister the hotkey when they are no longer needed
cleanup();

Changelog

[1.0.2]

  • Improve README

[1.0.1]

  • Preserve the user-defined hotkey in the error message

License

This package is released under the MIT License.