JQuery, check for arrow key pressed swith statement
-
21-06-2021 - |
Domanda
I've setup a keydown function and I want to do different things depending on whether the left, right, up or down arrow keys are pressed. That's working using a switch statement, but I'd also like to do something when ANY arrow key is pressed, but can't figure it out. My code:
$(document).keydown(function (e) {
var keyCode = e.keyCode || e.which,
arrow = {left: 37, up: 38, right: 39, down: 40 },
switch (keyCode) {
case arrow.left:
// do something left
break;
case arrow.right:
// do something right
break;
}
});
I would really just like a line of code where I could check for whether any arrow key is pressed, but can't figure it out, so for example:
case arrow:
// do something for any arrow keys
break;
Just using "case arrow doesn't seem to work. Could anyone help?
Thanks in advance!
EDIT: Thanks for your help everyone. Here's my final code, for anyone looking:
$(document).keydown(function (e) {
if (e.which >= 37 && e.which <= 40) {
$('p.key-notification').fadeOut('slow');
}
var keyCode = e.keyCode || e.which,
arrow = {left: 37, up: 38, right: 39, down: 40 },
switch (keyCode) {
case arrow.left:
// do something left
break;
case arrow.right:
// do something right
break;
}
});
Soluzione
Why does that also have to be within your switch
statement?
Make a separate if
statement after your switch:
if (keyCode >= 37 && keyCode <= 40) {
// run your code here
}
Altri suggerimenti
A single switch
statement isn't able to match on multiple conditions - you can have fall-through, but that doesn't evaluate the expression on subsequent cases and won't achieve your desired effect. I'd do it like this:
if (keyCode >= 37 && keyCode <= 40) {
// do any processing for _any_ arrow key here if it should happen
// before individual arrow key processing
switch (keyCode) {
case arrow.left:
// do something left
break;
case arrow.right:
// do something right
break;
}
// do any processing for _any_ arrow key here if it should happen
// after individual key processing
}
Putting the switch
inside the if
statement saves evaluating it when none of the cases would've matched. (So obviously if you later wanted the switch
to handle other keys you'd need to move it out of the if
.)
If you needed to do something similar for keys that didn't have consecutive key codes then obviously you couldn't use a >= && <=
condition so you'd do something like this:
if (keyCode === arrow.left || keyCode === arrow.right
|| keyCode === arrow.up || keyCode === arrow.down) {
This should work for you needs if I understand you correctly.
Another approach that adds to readability
var arrow = { left: 37, up: 38, right: 39, down: 40 };
Any of them
switch (evt.keyCode) {
case arrow.right:
case arrow.left:
case arrow.up:
case arrow.down:
// Do something
break;
}
One of
switch (evt.keyCode) {
case arrow.right:
// Do right
break;
case arrow.left:
// Do left
break;
case arrow.up:
// Do up
break;
case arrow.down:
// Do down
break;
}