As you already know, Enter key is part of the keyboard. That makes it obvious to use the KeyboardEvent constructor to trigger any keypress. KeyboardEvent describes any kind of user interaction with the keyboard.
Whenever the user presses any key on the keyboard, it triggers 3 keyboard events keydown, keypress, or keyup. I suggest you have a look over KeyboardEvent MDN docs to learn more about it since explaining its full functionality is out of the scope of this tutorial.
The following example is pretty straightforward. We want to trigger Enter keypress and Enter + Shift keypress programmatically when the user clicks on a button. Please have a look over the code example and steps given below.
We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
We have centered align the content by using the style attribute on the div element.
We have selected 2 elements (button and h1) using the document.querySelector() method and stored them in btn and result variables.
We have attached the keydown event listener to the body element. The event object contains key and shiftKey properties.
If the key property of the event object is equal to “Enter”, we will display “Enter Key Pressed” in the h1 element.
If the above condition is met and also shift key is pressed simultaneously which we will identify when shiftKey is equal to true, we will display “Enter + Shift Key Pressed” in the h1 element.
We have attached the click event listener to the button element.
Inside the click event handler function, we are creating 2 keydown events using the KeyboardEvent constructor. The constructor takes 2 parameters and the second parameter is optional. Please create one event at a time and comment out the other one as shown in the code below.
For both keydown events, we have passed “keydown” to the first parameter and the second parameter is an object with a key property that is equal to “Enter”.
In the second event, we have additional shiftKey property which is equal to true. Use this only, if you want to trigger Shift + Enter keypress.
We are using document.document.body.dispatchEvent() to dispatch keyboard event to the body element.