simulate keypress in javascript

How to Simulate KeyPress in JavaScript

JavaScript allows you to easily create as well as handle different types of events on your web pages. Often we need to create event handlers for clicks and keypresses on our site. But sometimes you may need to simulate keypress in JavaScript. In this article, we will learn how to simulate keypress in JavaScript.


How to Simulate KeyPress in JavaScript

We will need to create a Keypress event on our web page for our purpose. We will do that using the following command.

var keyboardEvent = document.createEvent('KeyboardEvent');

Next, we set an initMethod variable depening on whether the above event has been defined or not.

var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';

Then we configure our keyboard event as shown below. Here is an example of keydown event. You can customize it as per your requirement.

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
);

Lastly, we dispatch the event so that it actually occurs.

document.dispatchEvent(keyboardEvent);

If the above code does not work for you, then try using the following code in createEvent() function to create a regular event instead of creating a KeyboardEvent. This happens in some browsers due to compatibility issues.

document.createEvent('Event')

In the above code, we have dispatched event on document object but you can also dispatch it on DOM element or window object. For example, here is the code to call keypress event on a DOM element such as textbox and enter value ‘a’ in it.

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

Let us say you have the following HTML.

<input/>
<button id="dispatchButton">Press to dispatch event </button>

Here is a simple code to simulate keypress when you click the dispatchButton button and enter value ‘a’ in the input element.

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);

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

In this article, we have learnt how to simulate keypress event using JavaScript. Of course, you can also do this using third-party libraries like jQuery.

Also read:

How to Call Function Using Variable Name in JavaScript
How to Detect Tab/Browser Closing in JavaScript
How to Include Another HTML in HTML File
How to Call JS Function When Page is Loaded
How to Match Exact String in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *