Is it possible to simulate key press events programmatically?

You can dispatch keyboard events on an EventTarget (element, Window, Document, others) like this:

element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));

However, dispatchEvent might not update the input field value, and it might not trigger behavior that a regular keyboard press does, likely because of the Event.isTrusted property, which I don’t know if there’s a way to get around

But you can also change an input by setting its value.

element.value += "a";


let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
   element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>

You can add more properties to the event as needed, as in this answer. Take a look at the KeyboardEvent documentation

element.dispatchEvent(new KeyboardEvent("keydown", {
    key: "e",
    keyCode: 69, // example values.
    code: "KeyE", // put everything you need in this object.
    which: 69,
    shiftKey: false, // you don't need to include values
    ctrlKey: false,  // if you aren't going to use them.
    metaKey: false   // these are here for example's sake.


Also, since keypress is deprecated you can use keydown + keyup, for example:

element.dispatchEvent(new KeyboardEvent('keydown', {'key':'Shift'} ));
element.dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Shift'} ));

Leave a Comment