Bind Multiple Keys to Keypress Event
Solution 1
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
}
});
Solution 2
Why not use if
rather than switch
?
$(document).keydown(function(e) {
if ((e.keyCode === 37) || (e.keyCode === 39)) {
e.preventDefault();
alert("Arrow Key");
}
});
Solution 3
You can use the case fallthrough:
$(document).keydown(function(e) {
switch(e.which) {
case 39:
case 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
Note that I'm using e.which
instead of e.keyCode
to make it work in all browsers (jQuery automatically assigns the property which actually contains the key code to e.which).
mcbeav
Updated on July 15, 2022Comments
-
mcbeav almost 2 years
I am currently using this Javascript keypress 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; } });
-
Tim Down over 13 yearsNo. For a
keydown
event,keyCode
is the correct property in all browsers. Perhaps you're thinking ofkeypress
events? -
mcbeav over 13 yearsI am about to test this out, but just to be sure, this is going to fire on the pressing of both keys, a combination, right?
-
Zain Shaikh over 13 yearsno, this code is not for
combination
, this is foreither one of them is pressed
. -
mcbeav over 13 yearsI am looking for something that would work for a combination of keys pressed. Any ideas?
-
mcbeav over 13 yearsYeah, this will do, i don't know why i preferred to use a switch, but i guess it really doesn't matter. Thanks again for the help. Much appreciated.
-
mcbeav over 13 yearsI know this doesnt' have anything to do with this post but if you see this, maybe you could help me with the jQuery LazyLoad plugin if you get a minute?
-
ThiefMaster over 13 yearsJust curiosity, but how can this be your accepted answer with the while you are stating "I am looking for something that would work for a combination of keys pressed. Any ideas?" in another comment?
-
mcbeav over 13 yearsThank you, i really appreciate the help. Yeah this is actually more fo what I was looking for. Thanks again.
-
JonSnow over 9 yearsPerfect, perfect, perfect - exact what I was looking for this morning!!