1

Using Vanilla JS (not jQuery), I want to dispatch a keyboard event with some info about the key that should be pressed, and I want the result to appear in the text area.

var textarea = document.querySelector('textarea');

var keyEvent = new Event('keypress', {
  key: 'a',
  location: 0,
  which: 65,
  code: 'KeyA'
});

textarea.dispatchEvent(keyEvent);
<textarea></textarea>

JS Fiddle Demo

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
TJBlackman
  • 1,895
  • 3
  • 20
  • 46
  • you are dispatching an event to the "air", you need to focus it on the textarea, but still I don't think it's possible: https://stackoverflow.com/questions/50219800/chrome-simulate-keypress-events-on-input-text-field-using-javascript – EugenSunic Dec 02 '19 at 22:14
  • Does this answer your question? [Chrome: Simulate keypress events on input text field using javascript](https://stackoverflow.com/questions/50219800/chrome-simulate-keypress-events-on-input-text-field-using-javascript) – EugenSunic Dec 02 '19 at 22:15
  • 1
    Does this answer your question? [Dispatching a KeyboardEvent fails to produce the character in a textarea](https://stackoverflow.com/questions/52910309/dispatching-a-keyboardevent-fails-to-produce-the-character-in-a-textarea) – Heretic Monkey Dec 02 '19 at 22:16
  • Thanks for the links. I'll review them. – TJBlackman Dec 02 '19 at 22:18
  • It is not supposed to work, even after you fix `Event` to [`KeyboardEvent`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) – tevemadar Dec 02 '19 at 22:20
  • 1
    Does this answer your question? [Dispatching keyboard event doesn't work in JavaScript](https://stackoverflow.com/questions/20163708/dispatching-keyboard-event-doesnt-work-in-javascript) – hc_dev Dec 02 '19 at 22:26

0 Answers0