jQuery Capture Multiple Key Press Combinations
Share
You may have read a previous post on how to capture a single key press using jQuery. In this example you can capture multiple key presses in combinations.
The array (arrShortCut) defines the following:
- a name (for reference only)
- a keypad code
- a function to execute in the variable iShortCutControlKey
if the control key activates the state” to keyup if the control key “off state”, if verified a key keydown a “no control” to “active status” look in the array if there is a preset for that key, if the function call “execShortCut” that … executes the function;
//to test use CTRL + Z = alert (2)
var arrShortCut = [{ name: 'test1', key: 15, fx: 'alert(1);' }, { name: 'test2', key: 90, fx: 'alert(2);'}];
var iShortCutControlKey = 17; // CTRL;
var bIsControlKeyActived = false;
$(document).keyup(function(e) {
if (e.which == iShortCutControlKey) bIsControlKeyActived = false;
}).keydown(function(e) {
if (e.which == iShortCutControlKey) bIsControlKeyActived = true;
if (bIsControlKeyActived == true) {
jQuery.each(arrShortCut, function(i) {
if (arrShortCut[i].key == e.which) {
execShortCut(arrShortCut[i].fx);
return;
}
});
}
});
function execShortCut(fx) {
eval(fx);
}