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?
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
)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With