I've read and tried the solutions for this question but none of them work as I expect.
In the code snippet below I register two event listeners and see both callbacks fire as a response to the keydown
event on the input
and document
.
However, my expectation is that when this line of code runs there's an additional text entered into the input, a
.
input.dispatchEvent(keyEvent);
In other words, I expect that invoking dispatchEvent
on the input
element with KeyboardEvent
as an argument should add text to the input, however it does not.
It does invoke the callbacks registered with the eventListener.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="input">
<script>
const input = document.getElementById('input')
input.addEventListener('keydown', (e) => {
console.log('Keydown on Input: ', e.key)
})
document.addEventListener('keydown', (e) => {
console.log('Keydown on Doc: ', e.key)
})
function focusInputThenFireEventKeyboardEvents() {
input.value = 'I want '
input.focus()
input.dispatchEvent(new Event('focus'));
input.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
input.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
var keyEvent = new KeyboardEvent("keydown", { key: "a", char: "a", shiftKey: true });
var keyEvent2 = new KeyboardEvent("keydown", { key: "d", char: "d", shiftKey: true });
input.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent2);
}
setTimeout(focusInputThenFireEventKeyboardEvents, 500)
</script>
</body>
</html>