Capturing + (plus key) with keymaster.js

We use keymaster.js to power the keyboard shortcuts on a new product under development at work. It’s a great little javascript library for detecting key-presses from users.

For this product we wanted to capture the “+” key for when users wanted to Add something to their console. The confusion for me came from the fact the the “+” is used in the key() method for joining sequences of keys to get multi-key dispatching (e.g. pressing Control and Return at the same time).

It’s a pretty simple solution, but I couldn’t find it anywhere so thought I’d post here just in case someone else wants to do the same thing. As it turns out, “=” and “+” share the same key code in javascript, so the following will allow capturing of the plus key from both the numeric keypad as well as on the standard keyboard.

<script type="text/javascript" src="keymaster.min.js"></script>
<script type="text/javascript">
(function() {
  var myFunc = function() {
    console.log("User hit the + key");
  key('=,shift+=', myFunc);

An unfortunate by-product of the above, however, is that the same function will fire if the user hits just the “=” key. A pretty trivial trade-off IMHO. If anyone can think of a way to differentiate between the two let me know!


I received the very helpful information from Mo:

“=” and “+” don’t always share the same keyCode for keydown events in JavaScript. I’ve had similar issues in the past when handling keyboard events. Frustratingly, key codes can be different across different browsers and operating systems.

  • In Safari & Chrome on Mac, = has code 187 and + has code 187.
  • In Firefox on Mac, = has code 61 and + has code 107.
  • In Firefox on Windows, = has code 107 and + has code 107.
  • In IE on Windows, = has code 187 and + has code 107.
  • In Chrome on Windows, = has code 187, + has code 187 and the numpad + has code 107.

To differentiate between codes that are the same for a keydown, I think you’d have to look at the keypress charCodes for them as they will be different. But as you say, what you’ve got is a trivial trade-off so it’s probably not worth the effort!

I hadn’t seen keymaster.js before – looks pretty neat! You could add more to its special mappings array to declare “plus: 107″ and “equals: 61″ then have key(‘=, shift+=, plus, shift+equals’, …) to be able to catch +’s for IE and Firefox Mac.

comments powered by Disqus