I want to simulate keydown
events on a given textarea element in an html page. Since I am using Chrome, I called initKeyboardEvent
on my variable and I passed the keyCode
I want to type into the textarea. Here is what I tried:
var keyEvent = document.createEvent('KeyboardEvent');
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
inputNode.dispatchEvent(keyEvent);
In this code I'm typing the letter m however the textarea is only getting the keyCode
13 which is the Enter key. So, I tried an override code I saw online that sets the value to keyCodeVal
, but with no success.
var keyEvent = document.createEvent('KeyboardEvent');
Object.defineProperty(keyEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0);
keyEvent.keyCodeVal = 77;
inputNode.dispatchEvent(keyEvent);
Does anyone have an idea how to set the keyCode
value?