After being asked once again to add some keyboard shortcuts to a web application, and being tired of doing things like:
$(document).keydown(function(e){
if (e.which == 13) //enter
reloadResults();
else if (e.which == 37) //left arrow
previousPage();
else if (e.which == 39) //right page
nextPage();
});
I decided it would be nice if I could write instead something like this:
$(document)
.onEnterKeyDown(reloadResults)
.onLeftArrowKeyDown(previousPage)
.onRightArrowKeyDown(nextPage);
I looked around, and although there are plenty of libraries to handle keyboard input, none had a syntax like this. Because of this I created easykeyjs.
Here are a few examples of how to use it:
Register an event handler for when F11 is pressed on an element with id="myInput"
while preventing the browser from going to full screen mode:
$('#myInput').onF11KeyDown(function(e) {
//do something in response to F11 being pressed
e.preventDefault(); //prevent the browser from going full screen
//e.stopPropagation(); //prevent the event from bubbling up, if you want to do both, just return false;
});
Register an event handler for pressing “Control + s”:
$(document).onSKeyDown(save, $.easyKey.options.withControlPressed);
Register an event handler for releasing “Control + s”:
$(document).onSKeyUp(printSaved, $.easyKey.options.withControlPressed);
Register an event handler for “Control + Alt + Shift + a”:
$(document).onAKeyDown(selectAll,
$.easyKey.options.withControlPressed
| $.easyKey.options.withAltPressed
| $.easyKey.options.withShiftPressed);
Register an event handler for i that runs both on key down and then on key up:
$(document).onKey($.easyKey.keyCodes.i,
function(e) { $('#myInput').toggleClass("highlight"); },
$.easyKey.options.onKeyDown | $.easyKey.options.onKeyUp);
To run this you need jQuery (any recent version should be fine, jQuery 1.4+).
Go download easykeyjs from here.
The github repo is here.