Listen for multiple keypress

pure js

by Preston Badeer

JavaScript

// This listens for keypress of entire document
// If you change this to an element, it will
// only listen when that element is in focus
document.onkeypress = function (e) {
    // These need to be numbers, not strings!
    // Order doesn't matter
    var myKeys = [20, 13, 11, 54];

    // Which works in some browsers and
    // keycode works in others. This will
    // use whichever works.
    var keyPressed = e.which || e.keyCode;

    // indexOf will look inside the array for
    // any occurance of e.keyCode, if none
    // are found it returns -1. So this just
    // checks if the keycode pressed exists
    // in the array.
    if (myKeys.indexOf(keyPressed) != -1) {
        console.log("You pressed one of the keys!");
    }
};