I am trying to dispatch events programatically for keyboard and mouse events.
So far there are few things I have tried. Right now I am able to dispatch mouse events programatically and see the changes:
const element = document.getElementById("element");
const event = new Event('click', {bubbles: true});
element.dispatchEvent(event);
Above method is working fine for Mouse Event. And I have tried following method for keyboard events:
const element = document.getElementById("input-element");
const event = new KeyboardEvent('keypress', {'key': 'e'});
element.dispatchEvent(event);
It seems here that the event is being executed, but the values are not being updated in the input field.
There are a number of events that occur when you press a key. None of them result in an input value being changed, but you can use this function to approximate what happens when a key is pressed.
const element = document.getElementById("input-element");
const key = 'e';
var success = triggerKey(key, element);
console.log(success?'success':'fail');
function triggerKey(key, element){
if(!/^[a-z]$/.test(key)) return false;
if(!['INPUT','TEXTAREA'].includes(element.tagName)) return false;
const events = ['keydown', 'keypress', 'textInput', 'keyup'];
events.forEach(event_name=>{
const opts = 'textInput' === event_name ? {
inputType: 'insertText',
data: key
} : {
key: key,
code: `Key${key.toUpperCase()}`
};
const event = 'textInput' === event_name ?
new InputEvent('input', opts) :
new KeyboardEvent(event_name, opts);
element.dispatchEvent(event);
if('textInput' === event_name) element.value += key;
});
return true;
}
<input id="input-element">