Categories
Coding

JavaScript keypress detection script

Method 1

Detect = {};
Detect.keydown = function(k) {
    var oEvent = document.createEvent("KeyboardEvent");

    // Chromium Hack
    Object.defineProperty(oEvent, "keyCode", {
                get : function() {
                    return this.keyCodeVal;
                }
    });     
    Object.defineProperty(oEvent, "which", {
                get : function() {
                    return this.keyCodeVal;
                }
    });     

    if (oEvent.initKeyboardEvent) {
        oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, true, false, false, false, k, k);
    } else {
        oEvent.initKeyEvent("keydown", true, true, document.defaultView, true, false, false, false, k, 0);
    }

    oEvent.keyCodeVal = k;

    if (oEvent.keyCode !== k) {
        alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
    }

    document.dispatchEvent(oEvent);
}
Detect.keydown(65);

Method 2

document.dispatchEvent(new window.KeyboardEvent("keydown", {key: "a", char: "a", keyCode: 65, ctrlKey:false}));

Method 3

var e = jQuery.Event("keydown");
e.which = 65;       // # G code value
e.ctrlkey = false;     // control key pressed
jQuery(document).trigger(e);// trigger event on document