Search code examples
javascriptjqueryswitch-statementarrow-keys

jQuery e.which in switch statement


In the below switch statement when left key is pressed, it alerts left and when top key is pressed it alerts top. How can i make a case for combination of both shift and left key.

$(document).keydown(function(e) {
    switch (e.which) {
        case 37: alert('left'); //left arrow key
            break;
        case 38: alert('top');; //up arrow key
            break;
        case ??: alert('shift + left'); //How can i make this repond to the combination of shift + left arrow keys.
            break;
    }
});

Solution

  • The shift key is a modifier, and can be checked in the case statement for the left key.

    $(document).keydown(function(e) {
        switch (e.which) {
         case 37:
            if (e.shiftKey) {
                alert('shift+left'); // shift and left arrow key
            }
            else {
                alert('left'); //left arrow key
            }
            break;
         case 38:
            alert('top'); //up arrow key
            break;
        }
    });
    

    Demo: http://jsfiddle.net/ZL9Fx/1/