Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Avoiding hardcoded keycodes [duplicate]

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?

like image 920
Randomblue Avatar asked Jan 11 '13 11:01

Randomblue


2 Answers

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) { ... }
like image 171
VisioN Avatar answered Nov 13 '22 21:11

VisioN


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

"\r".charCodeAt(0)
like image 36
Randomblue Avatar answered Nov 13 '22 19:11

Randomblue