Simulate a Keypress Event Programmatically in JavaScript

In this article, we learn how to simulate a keypress event programmatically in JavaScript using event handlers.

To simulate a keypress event programmatically in JavaScript, use the dispatchEvent() method.

The dispatchEvent() method sends an Event to the object, (synchronously) invoking the affected EventListeners in the appropriate order.

The dispatchEvent() method accepts Event object as parameter.

To trigger it programmatically, you can pass Event to the dispatchEvent() method.

For example, Trigger keypress event on page load.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simulate a Keypress Event</title>
</head>
<body>
    <script>
        window.addEventListener('keydown', (e) => {
            // 👇️ KeyboardEvent {isTrusted: false, key: 'h', code: '', location: 0, ctrlKey: false, …}
            console.log(e)
        })

        window.dispatchEvent(new KeyboardEvent('keydown', {
            'key': 'h'
        }));
    </script>
</body>
</html>

First, we write an addEventListener method with a keydown to listen to the keypress in the browser.

Then to trigger an event, we write the dispatchEvent() method with the KeyboardEvent instance.

We passed the type of event keydown as the first parameter and options to set the event in the second parameter to the KeyboardEvent instance.

Now, whenever the page loads, dispatchEvent() is executed and logs the event from the callback function.

We can pass the following event types and options in the KeyboardEvent constructor.

Events we can pass to the KeyboardEvent object:

EventDescription
keydownOccurs when the key is pressed on the keyboard
keyupOccurs when the key is released

Options we can use with the KeyboardEvent object:

PropertyDescription
codeThe name of the key
keyCodeThe numeric code of the key
whichThe keyboard key number
shiftKeysets whether to press the shift key in addition to the key pressed
ctrlKeysets whether to press the control key in addition to the key pressed
metaKeysets whether to press the meta key in addition to the key pressed

The meta key is the command key on Mac keyboards and the Windows key on PC.

JavaScript
window.addEventListener('keydown', (e) => {
  // 👇️ KeyboardEvent {isTrusted: false, key: 'h', code: 'KeyH', location: 0, ctrlKey: false, …}
  console.log(e);
});

window.dispatchEvent(new KeyboardEvent('keydown', {
  key: "h",
  keyCode: 72,
  code: "KeyH",
  which: 72,
  shiftKey: false,
  ctrlKey: false,
  metaKey: false
}));

On the page load, our keypress event is triggered, and all options we passed to the keyboard event will be logged in the callback function of the event listener method.


Conclusion

Using the dispatchEvent() method, you can simulate a keypress event programmatically in JavaScript.


Learn More:

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp