Search code examples
jqueryswitch-statementarrow-keys

JQuery, check for arrow key pressed swith statement


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

}); 

Solution

  • 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
    }