Convert Figma logo to code with AI

RobertWHurst logoKeyboardJS

A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

2,090
224
2,090
11

Top Related Projects

➷ A robust Javascript library for capturing keyboard input. It has no dependencies.

11,641

Simple library for handling keyboard shortcuts in Javascript

A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.

A keyboard input capturing utility in which any key can be a modifier key.

A tiny (~650 B) & modern library for keybindings.

Quick Overview

KeyboardJS is a JavaScript library for handling keyboard events and managing keyboard shortcuts in web applications. It provides a simple and flexible API for binding and unbinding key combinations, as well as managing complex key sequences and locales.

Pros

  • Easy to use and intuitive API for binding keyboard shortcuts
  • Supports complex key combinations and sequences
  • Locale-aware, allowing for different keyboard layouts
  • Lightweight and has no dependencies

Cons

  • Limited documentation and examples
  • Not actively maintained (last update was in 2021)
  • May have compatibility issues with some newer browsers or frameworks
  • Lacks some advanced features found in more comprehensive libraries

Code Examples

Binding a simple key combination:

KeyboardJS.bind('ctrl + a', function(e) {
    console.log('Ctrl + A was pressed');
    e.preventDefault();
});

Binding a key sequence:

KeyboardJS.bind('↑ ↑ ↓ ↓ ← → ← → b a', function() {
    console.log('Konami code activated!');
});

Using press and release callbacks:

KeyboardJS.bind('shift + a', function(e) {
    console.log('Shift + A pressed');
}, function(e) {
    console.log('Shift + A released');
});

Getting Started

  1. Install KeyboardJS via npm:
npm install keyboardjs
  1. Import and use KeyboardJS in your project:
import KeyboardJS from 'keyboardjs';

// Bind a key combination
KeyboardJS.bind('ctrl + s', function(e) {
    console.log('Ctrl + S was pressed');
    e.preventDefault();
});

// Unbind a key combination
KeyboardJS.unbind('ctrl + s');

// Set a locale (optional)
KeyboardJS.setLocale('fr');

Competitor Comparisons

➷ A robust Javascript library for capturing keyboard input. It has no dependencies.

Pros of hotkeys-js

  • Lightweight and simple to use, with a smaller footprint
  • Supports a wider range of key combinations, including modifier keys
  • Better documentation and examples for quick implementation

Cons of hotkeys-js

  • Less robust event handling compared to KeyboardJS
  • Fewer advanced features for complex keyboard interactions
  • Limited support for custom key mappings

Code Comparison

hotkeys-js:

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;
  }
});

KeyboardJS:

KeyboardJS.bind('ctrl + a', function(e) {
  console.log('you pressed ctrl+a!');
});

KeyboardJS.bind('ctrl + b', function(e) {
  console.log('you pressed ctrl+b!');
});

Both libraries offer straightforward ways to bind keyboard shortcuts, but hotkeys-js allows for more compact code when defining multiple shortcuts. KeyboardJS provides a more verbose approach, which can be beneficial for complex scenarios or when more control over individual bindings is needed.

11,641

Simple library for handling keyboard shortcuts in Javascript

Pros of Mousetrap

  • Lightweight and simple to use, with a smaller footprint than KeyboardJS
  • Supports a wider range of browsers, including older versions
  • Includes built-in support for key sequences and key combinations

Cons of Mousetrap

  • Less flexible in terms of customization and advanced features
  • Doesn't support some complex key combinations that KeyboardJS can handle
  • Limited support for international keyboard layouts

Code Comparison

Mousetrap:

Mousetrap.bind('ctrl+shift+k', function() {
    console.log('Ctrl+Shift+K pressed');
});

KeyboardJS:

KeyboardJS.bind('ctrl + shift + k', function(e) {
    console.log('Ctrl+Shift+K pressed');
    e.preventRepeat();
});

Both libraries offer similar basic functionality for binding keyboard shortcuts. However, KeyboardJS provides additional features like preventRepeat() to avoid multiple triggers for held keys. Mousetrap's syntax is slightly more concise, while KeyboardJS offers more granular control over key events.

Overall, Mousetrap is better suited for simpler projects with basic keyboard shortcut needs, while KeyboardJS is more appropriate for complex applications requiring advanced key handling and customization.

A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.

Pros of Keymaster

  • Lightweight and simple API, making it easy to use for basic keyboard shortcuts
  • Supports key sequences and key combinations
  • Works across different browsers and platforms

Cons of Keymaster

  • Less actively maintained compared to KeyboardJS
  • Limited advanced features and customization options
  • Doesn't support some modern keyboard events and functionalities

Code Comparison

KeyboardJS:

KeyboardJS.bind('ctrl + shift + a', function(e) {
    console.log('Ctrl+Shift+A pressed');
    e.preventDefault();
});

Keymaster:

key('ctrl+shift+a', function() {
    console.log('Ctrl+Shift+A pressed');
    return false; // prevents default behavior
});

Both libraries offer similar syntax for binding keyboard shortcuts, but KeyboardJS provides more granular control over the event object and offers additional features for complex keyboard interactions.

KeyboardJS generally offers more robust functionality, better maintenance, and a wider range of features compared to Keymaster. However, Keymaster may be suitable for simpler projects where a lightweight solution is preferred.

A keyboard input capturing utility in which any key can be a modifier key.

Pros of Keypress

  • Supports complex key combinations and sequences
  • Provides a more intuitive API for handling key events
  • Offers better cross-browser compatibility

Cons of Keypress

  • Less actively maintained (last update in 2016)
  • Larger file size compared to KeyboardJS
  • Limited documentation and examples

Code Comparison

KeyboardJS:

KeyboardJS.bind('ctrl + shift + a', function(e) {
    console.log('Ctrl + Shift + A pressed');
});

Keypress:

var listener = new window.keypress.Listener();
listener.simple_combo("ctrl shift a", function() {
    console.log('Ctrl + Shift + A pressed');
});

Both libraries allow for binding key combinations, but Keypress offers a more object-oriented approach with its Listener class. KeyboardJS uses a simpler, more functional style. Keypress also provides more flexibility in defining key combinations, allowing for sequences and complex patterns.

While KeyboardJS is more lightweight and actively maintained, Keypress offers more advanced features for handling complex keyboard interactions. The choice between the two depends on the specific requirements of your project and the level of keyboard event handling complexity you need.

A tiny (~650 B) & modern library for keybindings.

Pros of tinykeys

  • Lightweight and minimalistic (only 0.5kb gzipped)
  • Simple API with a single function for binding keys
  • TypeScript support out of the box

Cons of tinykeys

  • Limited features compared to KeyboardJS
  • No support for key sequences or combos
  • Less flexibility in handling complex keyboard interactions

Code Comparison

tinykeys:

import tinykeys from "tinykeys";

tinykeys(window, {
  "Shift+D": () => {
    console.log("The 'Shift' and 'd' keys were pressed at the same time");
  },
});

KeyboardJS:

import keyboard from "keyboardjs";

keyboard.bind("shift + d", (e) => {
  console.log("The 'Shift' and 'd' keys were pressed at the same time");
});

Both libraries allow for binding keyboard shortcuts, but KeyboardJS offers more advanced features like key sequences, combos, and localization support. tinykeys focuses on simplicity and small bundle size, making it ideal for projects with basic keyboard shortcut needs. KeyboardJS is better suited for applications requiring complex keyboard interactions and more granular control over key events.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

KeyboardJS


Note Please Note: I've create a new libary called Keystrokes which serves the same purpose as KeyboardJS, but is more refined, and takes full advantage of modern browsers. If you are considering using KeyboardJS in a new project, I recommend checking out Keystrokes first.


Build Status NPM Version Downloads This Week License

KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to setup complex bindings. KeyboardJS also provides contexts. Contexts are great for single page applications. They allow you to scope your bindings to various parts of your application. Out of the box keyboardJS uses a US keyboard locale. If you need support for a different type of keyboard KeyboardJS provides custom locale support so you can create with a locale that better matches your needs.

KeyboardJS is available as a NPM module. If you're not using a build system like webpack, simply add keyboard.js or keyboard.min.js from the dist folder in this repo to your project via a script tag.

npm install keyboardjs

Note that all key names can be found in ./locales/us.js.

Setting up bindings is easy

keyboardJS.bind('a', (e) => {
  console.log('a is pressed');
});
keyboardJS.bind('a + b', (e) => {
  console.log('a and b is pressed');
});
keyboardJS.bind('a + b > c', (e) => {
  console.log('a and b then c is pressed');
});
keyboardJS.bind(['a + b > c', 'z + y > z'], (e) => {
  console.log('a and b then c or z and y then z is pressed');
});
keyboardJS.bind('', (e) => {
  console.log('any key was pressed');
});
//alt, shift, ctrl, etc must be lowercase
keyboardJS.bind('alt + shift > a', (e) => {
  console.log('alt, shift and a is pressed');
});

// keyboardJS.bind === keyboardJS.on === keyboardJS.addListener

keydown vs a keyup

keyboardJS.bind('a', (e) => {
  console.log('a is pressed');
}, (e) => {
  console.log('a is released');
});
keyboardJS.bind('a', null, (e) => {
  console.log('a is released');
});

Prevent keydown repeat

keyboardJS.bind('a', (e) => {
  // this will run once even if a is held
  e.preventRepeat();
  console.log('a is pressed');
});

Unbind things

keyboardJS.unbind('a', previouslyBoundHandler);
// keyboardJS.unbind === keyboardJS.off === keyboardJS.removeListener

Using contexts


  // these will execute in all contexts
  keyboardJS.bind('a', (e) => {});
  keyboardJS.bind('b', (e) => {});
  keyboardJS.bind('c', (e) => {});

  // these will execute in the index context
  keyboardJS.setContext('index');
  keyboardJS.bind('1', (e) => {});
  keyboardJS.bind('2', (e) => {});
  keyboardJS.bind('3', (e) => {});

  // these will execute in the foo context
  keyboardJS.setContext('foo');
  keyboardJS.bind('x', (e) => {});
  keyboardJS.bind('y', (e) => {});
  keyboardJS.bind('z', (e) => {});

  // if we have a router we can activate these contexts when appropriate
  myRouter.on('/', (e) => {
    keyboardJS.setContext('index');
  });
  myRouter.on('/foo', (e) => {
    keyboardJS.setContext('foo');
  });

  // you can always figure out your context too
  const contextName = keyboardJS.getContext();

  // you can also set up handlers for a context without losing the current context
  keyboardJS.withContext('bar', ()  =>{
    // these will execute in the bar context
    keyboardJS.bind('7', (e) => {});
    keyboardJS.bind('8', (e) => {});
    keyboardJS.bind('9', (e) => {});
  });

pause, resume, and reset


// the keyboard will no longer trigger bindings
keyboardJS.pause();

// the keyboard will once again trigger bindings
keyboardJS.resume();

// all active bindings will released and unbound,
// pressed keys will be cleared
keyboardJS.reset();

pressKey, releaseKey, and releaseAllKeys


// pressKey
keyboardJS.pressKey('a');
// or
keyboardJS.pressKey(65);

// releaseKey
keyboardJS.releaseKey('a');
// or
keyboardJS.releaseKey(65);

// releaseAllKeys
keyboardJS.releaseAllKeys();

watch and stop

// bind to the window and document in the current window
keyboardJS.watch();

// or pass your own window and document
keyboardJS.watch(myDoc);
keyboardJS.watch(myWin, myDoc);

// or scope to a specific element
keyboardJS.watch(myForm);
keyboardJS.watch(myWin, myForm);

// detach KeyboardJS from the window and document/element
keyboardJS.stop();

NPM DownloadsLast 30 Days