Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created November 16, 2022 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remarkablemark/d11276c60a108cd444ddc0c954436207 to your computer and use it in GitHub Desktop.
Save remarkablemark/d11276c60a108cd444ddc0c954436207 to your computer and use it in GitHub Desktop.
JavaScript dispatch keydown event programmatically
const KEY_CODE = {
ARROW_DOWN: 40,
BACKSPACE: 8,
ENTER: 13,
};
/**
* Dispatch keydown event.
*
* @param {number} keyCode
* @returns {void}
*/
function keydown(keyCode) {
const keyboardEvent = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
keyCode,
});
document.body.dispatchEvent(keyboardEvent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment