Build Custom Keyboard Shortcuts with Keyboard-ShortcutX

keyboard-shortcutx is a simple, lightweight JavaScript library that helps you manage keyboard shortcuts and hotkeys in your web applications.

Features:

  • Cross-framework compatibility: Works with vanilla JavaScript, React, Vue, and other modern frameworks.
  • React integration: Built-in support for component-level shortcuts with proper cleanup.
  • ESM-first architecture: Modern module system with legacy CommonJS support.
  • SSR-safe implementation: Server-side rendering compatibility built-in.
  • Modifier key support: Full support for Ctrl, Alt, Shift, and Meta key combinations.
  • Input element awareness: Optional behavior for form inputs and contenteditable elements.

Use Cases:

  • Command Palette: Implement a Cmd+K or Ctrl+K interface that allows users to search and execute commands, similar to the ones found in tools like VS Code, Slack, or Figma.
  • Global App Actions: Define application-wide hotkeys for common tasks. For example, you could bind Ctrl+S to save a document, Ctrl+N to create a new item, or Alt+T to toggle a theme.
  • Component-Specific Shortcuts: In a React or Vue application, you can define shortcuts that are only active when a specific component is mounted. This is useful for modal dialogs where Escape should close the dialog or for a media player where Space toggles play/pause.
  • Enhanced Accessibility: Create keyboard-driven navigation and actions to make your application more accessible to users who rely on keyboards instead of a mouse.

How to use it:

1. Install the keyboard-shortcutx package and import it into your JavaScript project.

# NPM
$ npm install keyboard-shortcutx
import { addShortcut } from "keyboard-shortcutx";
// OR
<script type="module">
  import { addShortcut, on, clearShortcuts } from "./index.js";
</script>

2. Create a new custom shortcut using the addShortcut function. The function takes the key combination and a callback function to execute. The event object e is passed to your callback, so you can call e.preventDefault() to stop the browser’s default behavior. Supported Key Combinations:

  • Modifiers: ctrl, alt, shift, meta (Command key on Mac)
  • Special aliases: mod (resolves to Ctrl on Windows/Linux, Cmd on Mac)
  • Function keys: f1 through f12
  • Navigation: enter, escape, tab, space, left, right, up, down
  • Character keys: Any letter, number, or symbol key
addShortcut("ctrl+k", (e) => {
  e.preventDefault();
  alert("ctrl+k");
});

3. The best way to manage shortcuts in your React app is within a useEffect hook. This lets you add the shortcut when the component mounts and automatically clean it up when the component unmounts.

import React from "react";
import { addShortcut, on, clearShortcuts } from "keyboard-shortcutx";
export default function App() {
  const [enabled, setEnabled] = React.useState(true);
  React.useEffect(() => {
    // Toggle button enable/disable with Ctrl+K
    const off1 = addShortcut("ctrl+k", () => {
      setEnabled((prev) => !prev);
    });
    // Log something with Shift+Alt+H
    const off2 = on("shift+alt+h", () => {
      console.log("Hello from Shift+Alt+H");
    });
    // Cleanup function
    return () => {
      off1();
      off2();
    };
  }, []); // Empty dependency array means this runs once on mount
  return (
    <div style={{ padding: "20px" }}>
      <h1>Keyboard ShortcutX Demo</h1>
      <button disabled={!enabled}>
        {enabled ? "I am Enabled ✅" : "I am Disabled ❌"}
      </button>
      <p>
        Press <b>Ctrl+K</b> to toggle the button <br />
        Press <b>Shift+Alt+H</b> to log a message in console
      </p>
    </div>
  );
}

4. Available options.

  • allowInInputs (boolean): Allow shortcuts to fire when focus is in input elements (default: false)
  • preventDefault (boolean): Automatically call preventDefault on the event (default: false)
  • stopPropagation (boolean): Stop event bubbling (default: false)
  • allowRepeat (boolean): Allow shortcuts to fire on key repeat events (default: false)
addShortcut("ctrl+k", (e) =&gt; {
  e.preventDefault();
  alert("ctrl+k");
},{
  allowInInputs: false, 
  preventDefault: true,
  stopPropagation: true,
  allowRepeat: false
});

5. More API methods.

  • on(keys, callback, options): Alias for addShortcut with identical functionality.
  • clearShortcuts(): Removes all registered shortcuts and detaches the global event listener.
  • removeShortcut(idOrKeysOrHandler): Removes specific shortcuts by ID, key combination, or handler function.
  • enable() / disable(): Globally enable or disable all shortcuts without removing registrations.

The post Build Custom Keyboard Shortcuts with Keyboard-ShortcutX appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading