Search code examples
javascriptkeypresskeyboard-events

how to set keycode value while triggering keypress event manually in pure javascript?


I am new to Javascript, though i have used JQuery well. But i cant find a better documentation for doing this . The click event need to be triggered only if i press enter key. so i need to write test case for this scenario.

function btnRepeatKeyDownEvent(e){
        if (e.keyCode === 13) {
            this.trigger('click', e);
        }
}

so far i have found this solution.

let keyboardEvent: KeyboardEvent = new KeyboardEvent('keypress', {'key': 'Enter'});
document.dispatchEvent(keyboardEvent);

but the above code always give keycode value as 0. i am more tired for finding the solution. As per MDN most of the functionalities are deprecated. i need to made this test case workable in chrome, firefox and IE11+ only not for old browsers.Please help me.


Solution

  • The keyCode and other properties are Read Only. So, you can fake it, taking advantage of JavaScript's Object.defineProperties function that does overwrite values:

    function makeKeyPressEvent(keyName, keyCode, charCode){
        var event = new KeyboardEvent('keypress');
        Object.defineProperties(event, {
            charCode: {value: charCode},
            keyCode: {value: keyCode},
            keyIdentifier: {value: keyName},
            which: {value: keyCode}
        });
        return event;
    }
    

    here is how to use it:

    window.addEventListener('keypress', function(event){console.log('key pressed!', event.keyIdentifier, event.keyCode, event.charCode, event)}, true);
    
    var enterKeyEvent = makeKeyPressEvent('Enter', 13, 13);
    
    window.dispatchEvent(enterKeyEvent);