hotkeys-js

repository·master·Indexed 27 days ago

https://github.com/jaywcjlove/hotkeys-js

A lightweight (~8kB) micro-library for defining and dispatching keyboard shortcuts with no dependencies. It supports single keys, key combinations, and custom scopes to group shortcuts. Compatible with Internet Explorer 6+, Safari, Firefox, and Chrome, it can be installed via npm or used directly in the browser via CDN (IIFE, UMD, and ES Module formats). Features include programmatic triggering, key state inspection, and a filter system to manage activation in input elements.

Tokens
5K
Snippets
12
Records
38
Agent score
88%

What's inside hotkeys-js

  1. React integration options

    master

    If you are working within a React application, consider these specialized libraries instead of using hotkeys-js directly:

    • react-hotkeys: A React component that listens to keydown and keyup keyboard events, defining and dispatching keyboard shortcuts.
    • react-hotkeys-hook: A React hook for using keyboard shortcuts in components (requires React 16.8+).
  2. Use hotkeys-js in the browser via CDN

    master

    You can use the library directly in HTML by linking to a CDN. The library provides several formats:

    Use this for simple <script> tag integration.

    <script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.min.js"></script>
    <script type="text/javascript">
    hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
      switch (handler.key) {
        case 'ctrl+a': alert('you pressed ctrl+a!');
          break;
        case 'ctrl+b': alert('you pressed ctrl+b!');
          break;
        case 'r': alert('you pressed r!');
          break;
        case 'f': alert('you pressed f!');
          break;
        default: alert(event);
      }
    });
    </script>

    UMD (Universal Module Definition)

    For CommonJS/AMD environments.

    <script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.umd.cjs"></script>

    ES Module

    For modern browsers with module support.

    <script type="module">
    import hotkeys from 'https://unpkg.com/hotkeys-js/dist/hotkeys-js.js';
    hotkeys('ctrl+a', function(event, handler){
      alert('you pressed ctrl+a!');
    });
    </script>
  3. Configure hotkey options

    master

    When defining hotkeys, you can pass an options object as the second argument to customize behavior:

    • scope (String): The scope this hotkey belongs to.
    • element (HTMLElement): The specific DOM element to bind the event to.
    • keyup (Boolean): If true, the callback triggers on both keydown and keyup.
    • keydown (Boolean): If true, the callback triggers on keydown.
    • splitKey (String): The separator for combination keys (default is +).
    • capture (Boolean): If true, the listener triggers during the capture phase.
    • single (Boolean): If true, only one callback is allowed (automatically unbinds previous ones).
  4. Basic usage of hotkeys-js

    master

    Import hotkeys from the library and call it with a key combination string and a callback function. The callback receives the event and a handler object.

    import hotkeys from 'hotkeys-js';
    
    hotkeys('f5', function(event, handler){
      // Prevent the default refresh event under WINDOWS system
      event.preventDefault()
      alert('you pressed F5!')
    });
    import hotkeys from 'hotkeys-js';
    
    hotkeys('f5', function(event, handler){
      // Prevent the default refresh event under WINDOWS system
      event.preventDefault()
      alert('you pressed F5!')
    });
  5. Check pressed keys and trigger events

    master

    The API provides several methods to inspect the current keyboard state or manually trigger events:

    • hotkeys.isPressed(key): Returns true if the specified key or keyCode is currently pressed.
    • hotkeys.getPressedKeyCodes(): Returns an array of key codes currently pressed.
    • hotkeys.getPressedKeyString(): Returns an array of key strings (e.g., ['⌘', 'A']) currently pressed.
    • hotkeys.trigger(key, [scope]): Manually triggers a shortcut event for the specified key and optional scope.
  6. Define shortcuts with hotkeys()

    master

    The primary way to use the library is by calling the hotkeys function directly. You can define single keys, key combinations, or multiple shortcuts separated by commas.

    To prevent default browser behavior (like page refresh), call event.preventDefault() inside the handler. To stop the event and prevent default browser events entirely, return false from the handler.

    Supported Modifiers:

    • , shift
    • option, , alt
    • ctrl, control
    • command,

    Special Keys: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete, f1 through f19, num_0 through num_9, num_multiply, num_add, num_enter, num_subtract, num_decimal, num_divide.

    // Single key
    hotkeys('a', function(event, handler){
      alert('you pressed a!')
    });
    
    // Key Combination
    hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){
      switch (handler.key) {
        case 'ctrl+a': alert('you pressed ctrl+a!');
          break;
        // ...
      }
    });
    
    // Preventing default behavior
    hotkeys('f5', function(event, handler) {
      event.preventDefault();
      alert('you pressed F5!');
    });
    
    // Stopping event propagation and default behavior
    hotkeys('ctrl+r, command+r', function() {
      alert('stopped reload!');
      return false;
    });
  7. Filter shortcut activation

    master

    By default, hotkeys are not enabled for INPUT, SELECT, or TEXTAREA elements. You can override this behavior by assigning a function to hotkeys.filter.

    hotkeys.filter should return true to allow the shortcut to trigger, or false to prevent it.

    // Allow all shortcuts everywhere
    hotkeys.filter = function(event) {
      return true;
    };
    
    // Dynamically change scope based on element type
    hotkeys.filter = function(event) {
      var target = event.target || event.srcElement;
      var tagName = target.tagName;
      hotkeys.setScope(
        /^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other'
      );
      return true;
    };
  8. Unbind hotkeys

    master

    Use hotkeys.unbind() to remove registered shortcuts.

    • hotkeys.unbind(keys): Unbinds the specified keys. If no scope is provided, it uses the current scope.
    • hotkeys.unbind(keys, scope): Unbinds keys for a specific scope.
    • hotkeys.unbind(keys, handler): Unbinds a specific function handler for a key.
    • hotkeys.unbind(): Unbinds all hotkeys.
  9. Define hotkeys with hotkeys()

    master

    The hotkeys() function is the primary way to register shortcuts. You can define single keys, combinations, or multiple shortcuts separated by commas.

    • Single key: hotkeys('a', callback)
    • Combinations: Use + as the default separator (e.g., ctrl+a). You can customize this using the splitKey option.
    • Multiple shortcuts: Separate them with commas (e.g., 'ctrl+a, ctrl+b').
    • Preventing defaults: Call event.preventDefault() inside the handler to stop browser default actions (like F5 refreshing).
    • Stopping propagation: Return false from the handler to stop the event and prevent default browser behavior.
  10. Configure hotkeys() with options

    master

    You can pass an options object as the second argument to hotkeys() to customize behavior:

    • scope<String>: Sets the scope in which the shortcut is active.
    • element<HTMLElement>: Specifies the DOM element to bind the event to.
    • keyup<Boolean>: Whether to trigger the shortcut on key release (default is keydown).
    • keydown<Boolean>: Whether to trigger the shortcut on key press.
    • splitKey<String>: Delimiter for key combinations (default is +).
    • capture<Boolean>: Whether to trigger the listener during the capture phase.
    • single<Boolean>: Allows only one callback function (automatically unbinds previous one).
    // Using scope and element
    hotkeys('o, enter', {
      scope: 'wcj',
      element: document.getElementById('wrapper'),
    }, function() {
      console.log('do something else');
    });
    
    // Using a custom splitKey
    hotkeys('ctrl-+', { splitKey: '-' }, function(e) {
      console.log('you pressed ctrl and +');
    });
    
    // Triggering on keyup
    hotkeys('ctrl+a', { keyup: true }, function(event, handler) {
      if (event.type === 'keyup') {
        console.log('keyup triggered');
      }
    });