5

Possible Duplicate:
JavaScript event.keyCode constants

This is my code:

$button.on('keyup', function (event) {
    // Detect an Enter keypress
    if(event.keyCode === 13) {
        doStuff();
    }
});

As you can see, the keycode 13 is hardcoded. Is there a (cross-browser) way to fish out that number in a more semantically meaningful way?

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547
  • 4
    If there is anything more semantic and clean than ASCII decimal codes, I've never seen it. Of course you can make a map `var keys = { enter: 13 }` and fish it through `event.code === keys.enter`, but I personally prefer to see the actual keycodes to be sure of what the script is doing without looking up an object's definition. And no, there are no cross-browser/platform issues with the Enter key as far as I'm aware. – Fabrício Matté Jan 11 '13 at 11:16
  • just define an object with keycodes a values , and key names as keys. There is no built in enum for that. – mpm Jan 11 '13 at 11:16
  • 4
    `"\r".charCodeAt(0)` or http://stackoverflow.com/questions/1465374/javascript-event-keycode-constants – Alex K. Jan 11 '13 at 11:17
  • Despite my initial comment, a key map may be useful when you're manoeuvring with many keys e.g. mapping all arrows keys would be more semantic than writing a number for each. `=]` – Fabrício Matté Jan 11 '13 at 11:19
  • 1
    @AlexK. Pretty smart hack to get the keycode of the carriage return without hardcoding it as OP requested, could be an answer imo. `=]` – Fabrício Matté Jan 11 '13 at 11:23
  • Just in case you want to use a separate package. Here's a lightweight npm package with these keycode constants https://github.com/kabirbaidhya/keycode-js – kabirbaidhya Apr 05 '16 at 05:39

2 Answers2

9

If you work with jQueryUI, you may use $.ui.keyCode constants:

keyCode: {
    BACKSPACE: 8,
    COMMA: 188,
    DELETE: 46,
    DOWN: 40,
    END: 35,
    ENTER: 13,
    ESCAPE: 27,
    HOME: 36,
    LEFT: 37,
    NUMPAD_ADD: 107,
    NUMPAD_DECIMAL: 110,
    NUMPAD_DIVIDE: 111,
    NUMPAD_ENTER: 108,
    NUMPAD_MULTIPLY: 106,
    NUMPAD_SUBTRACT: 109,
    PAGE_DOWN: 34,
    PAGE_UP: 33,
    PERIOD: 190,
    RIGHT: 39,
    SPACE: 32,
    TAB: 9,
    UP: 38
}

So in order to check for Enter pressed use:

if (event.keyCode === $.ui.keyCode.ENTER) { ... }
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • These of course aren't the only keyCodes that are constant cross-browser right? @Vision – Mark Pieszak - Trilon.io Apr 11 '13 at 14:09
  • 1
    The shifting sands of time have broken that link; [here's a working one](https://github.com/jquery/jquery-ui/blob/e9643f6bfc922773e29e3084e64de0240b547f32/ui/core.js#L29-L46) (as of October 2014) – Erin Call Oct 30 '14 at 22:34
2

To repeat Alex K.'s answer (I used):

"\r".charCodeAt(0)
Randomblue
  • 112,777
  • 145
  • 353
  • 547