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

Overview

keymaster.js

Keymaster is a simple micro-library for defining and dispatching keyboard shortcuts in web applications.

It has no dependencies.

It’s a work in progress (e.g. beta), so spare me your nerdrage and instead contribute! Patches are welcome, but they are not guaranteed to make it in.

Usage

Include keymaster.js in your web app*, by loading it as usual:

<script src="keymaster.js"></script>

Keymaster has no dependencies and can be used completely standalone. It should not interfere with any JavaScript libraries or frameworks.

*Preferably use a minified version that fits your workflow. You can run make to have UglifyJS (if you have it installed) create a keymaster.min.js file for you.

Defining shortcuts

One global method is exposed, key which defines shortcuts when called directly.

// define short of 'a'
key('a', function(){ alert('you pressed a!') });

// returning false stops the event and prevents default browser events
key('ctrl+r', function(){ alert('stopped reload!'); return false });

// multiple shortcuts that do the same thing
key('⌘+r, ctrl+r', function(){ });

The handler method is called with two arguments set, the keydown event fired, and an object containing, among others, the following two properties:

shortcut: a string that contains the shortcut used, e.g. ctrl+r scope: a string describing the scope (or all)

key('⌘+r, ctrl+r', function(event, handler){
  console.log(handler.shortcut, handler.scope);
});

// "ctrl+r", "all"

Supported keys

Keymaster understands the following modifiers: , shift, option, , alt, ctrl, control, command, and .

The following special keys can be used for shortcuts: backspace, tab, clear, enter, return, esc, escape, space, up, down, left, right, home, end, pageup, pagedown, del, delete and f1 through f19.

Modifier key queries

At any point in time (even in code other than key shortcut handlers), you can query the key object for the state of any keys. This allows easy implementation of things like shift+click handlers. For example, key.shift is true if the shift key is currently pressed.

if(key.shift) alert('shift is pressed, OMGZ!');

Other key queries

At any point in time (even in code other than key shortcut handlers), you can query the key object for the state of any key. This is very helpful for game development using a game loop. For example, key.isPressed(77) is true if the M key is currently pressed.

if(key.isPressed("M")) alert('M key is pressed, can ya believe it!?');
if(key.isPressed(77)) alert('M key is pressed, can ya believe it!?');

You can also get these as an array using...

key.getPressedKeyCodes() // returns an array of key codes currently pressed

Scopes

If you want to reuse the same shortcut for separate areas in your single page app, Keymaster supports switching between scopes. Use the key.setScope method to set scope.

// define shortcuts with a scope
key('o, enter', 'issues', function(){ /* do something */ });
key('o, enter', 'files', function(){ /* do something else */ });

// set the scope (only 'all' and 'issues' shortcuts will be honored)
key.setScope('issues'); // default scope is 'all'

// remove all events that are set in 'issues' scope
key.deleteScope('issues');

Filter key presses

By default, when an INPUT, SELECT or TEXTAREA element is focused, Keymaster doesn't process any shortcuts.

You can change this by overwriting key.filter with a new function. This function is called before Keymaster processes shortcuts, with the keydown event as argument.

If your function returns false, then the no shortcuts will be processed.

Here's the default implementation for reference:

function filter(event){
  var tagName = (event.target || event.srcElement).tagName;
  return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}

If you only want some shortcuts to work while in an input element, you can change the scope in the key.filter function. Here's an example implementation, setting the scope to either 'input' or 'other'. Don't forget to return true so the any shortcuts get processed.

key.filter = function(event){
  var tagName = (event.target || event.srcElement).tagName;
  key.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other');
  return true;
}

However a more robust way to handle this is to use proper focus and blur event handlers on your input element, and change scopes there as you see fit.

noConflict mode

You can call key.noConflict to remove the key function from global scope and restore whatever key was defined to before Keymaster was loaded. Calling key.noConflict will return the Keymaster key function.

var k = key.noConflict();
k('a', function() { /* ... */ });

key()
// --> TypeError: 'undefined' is not a function

Unbinding shortcuts

Similar to defining shortcuts, they can be unbound using key.unbind.

// unbind 'a' handler
key.unbind('a');

// unbind a key only for a single scope
// when no scope is specified it defaults to the current scope (key.getScope())
key.unbind('o, enter', 'issues');
key.unbind('o, enter', 'files');

Notes

Keymaster should work with any browser that fires keyup and keydown events, and is tested with IE (6+), Safari, Firefox and Chrome.

See http://madrobby.github.com/keymaster/ for a live demo.

CoffeeScript

If you're using CoffeeScript, configuring key shortcuts couldn't be simpler:

key 'a', -> alert('you pressed a!')

key '⌘+r, ctrl+r', ->
  alert 'stopped reload!'
  off

key 'o, enter', 'issues', ->
  whatevs()

alert 'shift is pressed, OMGZ!' if key.shift

Contributing

To contribute, please fork Keymaster, add your patch and tests for it (in the test/ folder) and submit a pull request.

TODOs

  • Finish test suite

Keymaster is (c) 2011-2013 Thomas Fuchs and may be freely distributed under the MIT license. See the MIT-LICENSE file.

Comments
  • adds key sequence support as a plugin. fixes #10.

    adds key sequence support as a plugin. fixes #10.

    keymaster.sequence.js is a plugin for keymaster.js that provides support for key sequences. Usage examples can be found in test.html. Only downside is that key sequences or single key events that are a part of other key sequences get triggered when typing the larger key sequence.

    opened by ghost 7
  • Add packaging for Meteor.js, http://meteor.com

    Add packaging for Meteor.js, http://meteor.com

    Hi Thomas,

    I'm a Meteor.js dev and volunteer package maintainer for Meteor. I've learned about keymaster.js from a wrapper package that we had and got out of date, and thought it would be great to have a direct integration from you in Meteor's package repository.

    This PR will let you directly publish updated versions of the library as they become available. All you have to do is create an account at https://meteor.com/ (click SIGN IN, then Create account). After you've done that, please let me know the name of the account, and I'll add you as a maintainer.

    I've already published the current version of the package on Atmosphere (Meteor's package directory). When you release new versions, you'll be able to publish them to Atmosphere by running meteor/publish.sh.

    Thanks & best regards, Dan, official Meteor integrations team

    opened by dandv 5
  • incorrect keycodes

    incorrect keycodes

    It seems keymaster is reporting invalid keycodes.

    If i log e.which from jquery and keymaster the results are different, keymaster's being the uppercase version

    $(body).on('keypress', function (e) {
    console.log(e.which);
    });
    key('a', function (e, handler) {
    console.log(e.which);
    });
    // hit's 'a' on keyboard
    // 65
    // 97
    

    if you lookup those codes, jquery is return 'a' and keymaster is returning 'A'

    opened by wayneashleyberry 4
  • Modifiers reset issue

    Modifiers reset issue

    All the modifier keys are reset when page get focus, then if you keep one of the modifier key down, but unfortunately it is ignored. (refer to #36) This change is using the event.[ctrlKey, altKey, shiftKey, metaKey] to check the modifiers key and can pass the tests. But don't know if any side effect here, please help to check, thanks.

    opened by clvrobj 4
  • Npm version is pretty old

    Npm version is pretty old

    I was a bit confused because your documentation talks about overwriting the filter function. I installed the library with ender (which showed the same version as in you master branch) and noticed that the filter function wasn't even defined. After poking around a bit I realized that the npm version is pretty old.

    I would suggest to put new changes in the develop branch, and also change developer versions to 1.0.3-dev so it's clear which version documentation is about.

    opened by enyo 4
  • Coffescript version

    Coffescript version

    As a weekend project to become more familar with coffeescript, I have converted your keymaster.js to coffeescript. Would be great if it would find its way into the master branch.

    opened by c-rack 4
  • Added IE6+ support.

    Added IE6+ support.

    I've added support for IE 6 and later.

    Also, I added in semicolons in after function declarations, as is best practice. Just remove them if you prefer it without.

    opened by scq 4
  • window.key namespace is too generic, consider moving to window.keymaster

    window.key namespace is too generic, consider moving to window.keymaster

    I've run into problems with other people's libs overwriting the global keyspace with key (ie window.key). Since key is such a generic name, this problem could be solved with using eg. keymaster instead.

    opened by knutole 3
  • Add bower.json

    Add bower.json

    I ran into issues installing keymaster via Bower as bower.json was not present and I needed the most recent commits but they were newer than the latest tagged release.

    I've added a bower.json file and bumped the patch version to 1.6.3.

    opened by elidupuis 3
  • Add bower.json for bower support

    Add bower.json for bower support

    opened by mrzmyr 3
  • Added the ability to check if a key is down

    Added the ability to check if a key is down

    When developing games, it's very common to test whether a key is down in a loop rather than relying on key events. This commit adds two methods that let you check to see if a key is down, isKeyPressed() and getPressedKeyCodes().

    opened by mimshwright 3
  • Delay

    Delay

    Is it possible to increase the delay time of a combination? I have longer combinations on my web app like 'a r c g' or 'a r c g k' and they take a bit time to think & press.

    opened by tifDev 0
  • ctrl+enter dont work

    ctrl+enter dont work

    Hi, @madrobby @okonet @agnoster @devongovett @jlukic ctrl+enter dont work, this is my code:

    $('textarea').on('keydown', null, 'ctrl+enter', function (e) {
      // No coming, why?
    })
    
    opened by gongph 3
  • [Feature Request] Ability to switch back to previous scope

    [Feature Request] Ability to switch back to previous scope

    Just want to be able to set scope back to previous one without setting a variable, and without knowing what the previous scope was. In my current application, I have many components where when a specific component is mounted I want it to use its scope and when that component dismounts -> back to previous scope [my component doesn't need to know the previous scope].

    opened by TimothyIp 1
Releases(v1.6.3)
  • v1.6.3(Dec 17, 2014)

    This is a bugfix release that fixes several issues. Also, unbind now works with multiple keys. There's a bower.json now to make life easier for bower users.

    Source code(tar.gz)
    Source code(zip)
Owner
Thomas Fuchs
Thomas Fuchs
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Robert Hurst 2k Dec 30, 2022
A keyboard input capturing utility in which any key can be a modifier key.

Keypress Version 2.1.5 Keypress is a robust keyboard input capturing Javascript utility focused on input for games. For details and documentation, ple

David Mauro 3.2k Dec 28, 2022
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.

jQuery.Hotkeys #About jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting al

John Resig 2.6k Jan 2, 2023
⌨ Awesome handling of keyboard events

No Longer Actively Maintained If someone would like to take over maintainence, feel free to get in touch (@keithamus on twitter). I'll happily transfe

Keith Cirkel 1.2k Dec 6, 2022
Easily create UDP sockets and TCP servers that bind to ports

bind-easy Easily create UDP sockets and TCP servers that bind to ports. npm install bind-easy Usage const bind = require('bind-easy') // bind to any

Mathias Buus 37 Dec 16, 2022
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.

Hotkeys HotKeys.js is an input capture library with some very special features, it is easy to pick up and use, has a reasonable footprint (~3kb) (gzip

小弟调调™ 5.7k Jan 4, 2023
Simple library for handling keyboard shortcuts in Javascript

Mousetrap Mousetrap is a simple library for handling keyboard shortcuts in Javascript. It is licensed under the Apache 2.0 license. It is around 2kb m

Craig Campbell 11.3k Jan 3, 2023
A simple library for handling keyboard shortcuts with Alpine.js.

✨ Help support the maintenance of this package by sponsoring me. Alpine.js Mousetrap A simple library for handling keyboard shortcuts with Alpine.js.

Dan Harrin 102 Nov 14, 2022
Obsidian plugin to add keyboard shortcuts commonly found in code editors such as Visual Studio Code or Sublime Text

Code Editor Shortcuts This Obsidian plugin adds keyboard shortcuts (hotkeys) commonly found in code editors such as Visual Studio Code or Sublime Text

Tim Hor 143 Dec 30, 2022
Obsidian plugin to support a sequenced of keyboard shortcuts to run commands.

Sequence Shortcuts (Obsidian plugin) This plugin allows you to use a sequences of chords for shortcuts instead of single chords. Creating a hotkey You

Ruan Moolman 23 Dec 17, 2022
Browser extension to add more keyboard shortcuts to TweetDeck.

TweetDeck Shortcut Plus Browser extension to add more keyboard shortcuts to TweetDeck. Keyboard shortcuts Browse Browse tweet (default: alt+b) Browse

Ryo Nakamura 5 May 26, 2022
Browser extension to add more keyboard shortcuts to twitter.com.

Twitter Shortcut Plus Browser extension to add more keyboard shortcuts to twitter.com. Keyboard shortcuts Browse Browse links in background (default:

Ryo Nakamura 6 Jun 4, 2022
Remote Keyboard Tutoring System is a web-based system that can be attached to any keyboard synthesizer through a MIDI connector.

The Remote Keyboard Tutoring System is a web-based system that can be attached to any (electronic) keyboard synthesizer through a MIDI connector. Once our system is connected to the keyboard, the user can interactively learn, play or teach in combination with the web application that we provide.

Department of Computer Engineering, University of Peradeniya 3 Nov 15, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Micro.publish is an Obsidian plugin to publish notes directly to Micro.blog, written in TypeScript

Micro.publish Micro.publish is a community maintained plugin for Obsidian to publish notes to a Micro.blog blog. Installing This plugin will be availa

Otavio Cordeiro 14 Dec 9, 2022
This experimental library patches the global custom elements registry to allow re-defining or reload a custom element.

Redefine Custom Elements This experimental library patches the global custom elements registry to allow re-defining a custom element. Based on the spe

Caridy Patiño 21 Dec 11, 2022