Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  183] [ 3]  / answers: 1 / hits: 16468  / 14 Years ago, sat, november 13, 2010, 12:00:00

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;
}
});

More From » jquery

 Answers
126

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
}
});

[#94971] Thursday, November 11, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jailynbethanies

Total Points: 686
Total Questions: 119
Total Answers: 99

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
;