3

I want to use hotkeys in one of my pages. However, it seems that the only key that can be detected in my hotkeys is the Enter Key.

$(document).keypress(function(e) {
    var key = e.which;
    switch (key)
    {
        case 72:
          alert("H");
          break;
        case 82:
          alert("R");
          break;
        case 66:
          alert("B");
          break;
        case 13:
          alert("ENTER");
          break;
        default:
          alert("Invalid");
    }
});

Reference of key code values: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

KevinT.
  • 272
  • 6
  • 16

1 Answers1

5

According to MDN (via the jQuery docs for event.which), e.which returns Unicode character codes, so H could be either 72 or 104 (h) depending on text case.

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property

Example fiddle

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • This answered my question. Thanks. But I still have a question. I want to have multiple hotkeys, as I've said in the question, and I want to use the JS switch instead of multiple `if`s and `if...else`. Is it possible to use 2 cases on a single function? something like: `switch(key) {` `case 72 || case 104: //function to be called;` `break;` `}` Thanks again in advance. – KevinT. Sep 18 '13 at 12:54
  • @KevinHandogTresuelo In this case you need to either need to use the modifier keys (Shift, Alt, Ctrl) or else store the currently pressed/released keys in a variable. It's all discussed in [this question](http://stackoverflow.com/questions/4954403/can-jquery-keypress-detect-more-than-one-key-at-the-same-time) – CodingIntrigue Sep 18 '13 at 12:58