1

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?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Hoff
  • 37,058
  • 17
  • 69
  • 95
  • What type of event are you trying to trigger? A JS native code or a third-party code? Maybe there is a clear way to achieve the same results. – Pedro Lima Feb 27 '20 at 13:33
  • @PedroLima I'm trying to trigger a 'keypress' event, as mentioned in the title and in the code. I want to simulate a user entering text into an input field. – Hoff Feb 27 '20 at 13:36
  • Please see [this](https://stackoverflow.com/questions/20163708/dispatching-keyboard-event-doesnt-work-in-javascript) answer or [this answer](https://stackoverflow.com/questions/50219800/chrome-simulate-keypress-events-on-input-text-field-using-javascript?noredirect=1&lq=1). dispatchEvent won't update your input content – Nick Parsons Feb 27 '20 at 13:51
  • updated my answer, you need to handle the press on the element, a dispatched keyboard event will have keyCode 0. – MiK Feb 27 '20 at 14:12

1 Answers1

2

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);" />
MiK
  • 888
  • 3
  • 16