2

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;
    }
});
Pinkie
  • 10,126
  • 22
  • 78
  • 124

1 Answers1

7

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/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • Thanks. It works great. I tried the same thing before using the conditional shortcut `e.shiftKey ? alert('shift+left') : alert('left');` and i also tried `e.which==16 ? alert('shift+left') : alert('left');` and it didn't work. Is there a reason why this shortcut doesn't work. – Pinkie May 12 '11 at 21:45
  • 1
    @Pinkie, try `alert(e.shiftKey ? 'shift+left' : 'left')` – Xyan Ewing May 12 '11 at 21:48
  • You could really shorten this rather than a constant rewrite of if else by moving your if statement to inline in the alert. For example: `switch (e.which) { case 37: alert(((e.shiftKey) ? "shift+" : "")+"left"); }` – SpYk3HH Jan 13 '12 at 17:15
  • @SpYk3HH: Yes, I could use the ternary operator, but I highly doubt that the code is going to `alert` and that's it. I assume there will be more code in the `if` and `else` blocks. In that case using `?:` won't help at all. Oh, btw: Pinkie (the OP) and Xyan Ewing already pointed this out in the comments above. Also my comment above also already shows this (http://jsfiddle.net/ZL9Fx/2/). – gen_Eric Jan 13 '12 at 17:19