Is it possible to simulate key press events programmatically?

Is it possible to simulate key press events programmatically in JavaScript?


A non-jquery version that works in both webkit and gecko:

var keyboardEvent = document.createEvent('KeyboardEvent');
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';

keyboardEvent[initMethod](
  'keydown', // event type: keydown, keyup, keypress
  true, // bubbles
  true, // cancelable
  window, // view: should be window
  false, // ctrlKey
  false, // altKey
  false, // shiftKey
  false, // metaKey
  40, // keyCode: unsigned long - the virtual key code, else 0
  0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

You can dispatch keyboard events on an element like this:

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

However, dispatchEvent might not update the input field value. Also, 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


Example:

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
element.dispatchEvent(new KeyboardEvent('keydown', {
  'key': 'a'
}));
<input/>

You can add more properties to the event as needed, like 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'} ));

If you are ok to use jQuery 1.3.1:

function simulateKeyPress(character) {
  jQuery.event.trigger({
    type: 'keypress',
    which: character.charCodeAt(0)
  });
}

$(function() {
  $('body').keypress(function(e) {
    alert(e.which);
  });
  simulateKeyPress("e");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js">
</script>