Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement gmail-like hotkeys

I'd like to implement keyboard hotkeys in a web application. So far I've been using the jquery.hotkeys plugin, and it allowed me to implement simple hotkeys (e.g. single keystrokes like a).

Now to support some more complex navigation via the keyboard, I'd like to implement 'multi-key' hotkeys like in gmail, where for example pressing g (for 'go') followed by i (for 'inbox') takes you the the inbox.

Does anyone know of a javascript component (jquery plugin or similar) for that task? Or what would be a good approach to implement such hotkeys?

like image 331
M4N Avatar asked Feb 23 '12 15:02

M4N


2 Answers

There's a better solution to this using keymaster with the keymaster-sequence plugin.

The sources are here keymaster.js and here keymaster.sequence.js

Use them like this:

<script type="text/javascript" src="https://raw.github.com/madrobby/keymaster/master/keymaster.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/chevalric/keymaster-sequence/master/keymaster.sequence.min.js"></script>
<script>
key.sequence(["g","i"], function () {
  var el = document.getElementById("result");
  el.innerHTML = "You first pressed 'g', then you pressed 'i'";
});

</script>
<div id="result"></div>

Here's a small demonstration http://jsfiddle.net/Nwdyd/1/ which also shows collision handling (binding g as well as g i)

like image 193
ocodo Avatar answered Oct 07 '22 00:10

ocodo


Set a global boolean value when g is pressed. Then check if it's set when i is pressed. You can optionally implement a timeout on the g press so that you have limited time to press i afterwards.

var goPressed = false;
function hotkeyPressed (event) {
    if (event.keyCode == KEYCODE_FOR_G) {
        goPressed == true;
        //Optionally:
        setTimeout(clearPresses, 3000);
    }
    if (event.keyCode == KEYCODE_FOR_I && goPressed) {
        gotoInbox();
    }
}

function clearPresses() {
    goPressed = false;
}
like image 28
Matt Fellows Avatar answered Oct 07 '22 01:10

Matt Fellows