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,753
  • 72
  • 57
  • 129
Hoff
  • 38,776
  • 17
  • 74
  • 99
  • 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
  • 918
  • 4
  • 16
  • I don't know if I'd call that truly simulating a keypress. That's writing your own event handler that is similar, but it doesn't do the same thing as a keypress in all situations. E.g. If the target element already has a value string "EXAMPLETEXT" and the text cursor was already between "EXAMPLE" and "TEXT", the result of the above js would be "EXMPLETEXTa", not "EXMPLEaTEXT". It also won't trigger handlers that require an isTrusted==true. – Jacob C. May 11 '23 at 22:01