dispatchEvent Method
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.
5 replies on “How to Simulate a Keypress Event Programmatically with JavaScript?”
I want to paste/ enter data into input but isTrusted is false if data is enter programmatically, is there any way to get around this
You can assign any boolean expression to isTrusted
When i can assign the boolean expression ?
Where do I paste the code from you site?
Your code seems incomplete! Shouldn’t there be
script tags or something? Nothing works from you!
I need full code examples or I’m just stitching stuff
together and hoping it works.
here is your page I was At::
How to Simulate a Mouse Click using JavaScript?
I know your trying to teach people how this stuff works
and believe me I do want to learn, and I am learning
as I go ahead. But sometimes people need the code
right away. “Copy And Paste”. I need a solution now
I’ll learn later!
Edward
Thanks for reading.
It should run in JSFiddle if you paste the code there. If there’re any missing variables you can define them with whatever you want.