mcbeav mcbeav - 6 months ago 38
Javascript Question

Bind Multiple Keys to Keypress Event

I am currently using this Javascript kepypress code to fire events upon keypress:

$(document).keydown(function(e) {
switch(e.keyCode) {

case 39:
e.preventDefault();
alert("Arrow Key");
break;

case 37:
e.preventDefault();
alert("Arrow Key");
}
});


but what i am wondering is if i can instead of binding one key bind a combination of two keys. Could I possibly do something like:

$(document).keydown(function(e) {
switch(e.keyCode) {
case 39 && 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});

Answer

If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).

You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.

Example:

$(document).keydown(function(e) {
    if(e.which == 98 && e.ctrlKey) {
        // ctrl+b pressed
    }
});