Categories
JavaScript Answers

How to simulate keypress with JavaScript?

Spread the love

To simulate keypress with JavaScript, we can call the dispatchEvent method to trigger an event of our choice.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

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

to listen to the keydown event and trigger it.

We call addEventListener with 'keydown' to listen to the keydown event.

Then to trigger the keydown event, we call window.dispatchEvent with a KeyboardEvent instance.

We pass in the type of keyboard event to trigger into the first argument of the constructor.

And we pass in an object with the options to set in the event object into the 2nd argument.

Therefore, after dispatchEvent is run, then e.key should be 'a' when logged in the callback.

We can set more options in the object.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  key: "e",
  keyCode: 69,
  code: "KeyE",
  which: 69,
  shiftKey: false,
  ctrlKey: false,
  metaKey: false
}));

to set more options in the object.

keyCode is the numeric code of the key that we want to set.

code has the name of the key.

which has the keyboard key number.

shiftKey sets whether we want to press the shift key in addition to the key we’re pressing.

ctrlKey sets whether we want to press the Ctrl key in addition to the key we’re pressing.

metaKey sets whether we want to press the meta key in addition to the key we’re pressing.

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

When the event is triggered, we should see all the options logged in the addEventListener callback.

They should be in the same properties in the e object as in the options object we pass into the KeyboardEvent constructor.

We can write the same code with the keyup event.

We just replace 'keydown' with 'keyup' everywhere.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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