Hoff
Hoff

Reputation: 39816

Simulate keypress event (in plain js)

I'm looking for an example of how to simulate a keypress event in js.

The examples I've found all use the deprecated Event.initEvent method.

When I try using the recommended KeyboardEvent instead, it doesn't work - the input is not updated.

<input id="myInput" />

const element = document.getElementById('myInput')
const keypressEvent = new KeyboardEvent('keypress', {
  code: 'KeyA'
})
element.dispatchEvent(keypressEvent)

What is wrong or missing in the above code? Does the element need to take focus first or something like that?

Upvotes: 1

Views: 4403

Answers (1)

MiK
MiK

Reputation: 913

function emitKey() {
  const element = document.getElementById('myInput');
  element.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
}
function handleKeypress(target, event) {
  if(event.keyCode == 0 && event.key != "") {
    target.value += event.key;
  }
}

emitKey();
<input id="myInput" onkeypress="handleKeypress(this, event);" />

Upvotes: 2

Related Questions