Skip to content

Instantly share code, notes, and snippets.

@miadz
Forked from boazsender/keyboard-event-trigger.js
Created November 20, 2016 13:07
Show Gist options
  • Save miadz/81def940a59058a8912116acc576fa17 to your computer and use it in GitHub Desktop.
Save miadz/81def940a59058a8912116acc576fa17 to your computer and use it in GitHub Desktop.
Dispatch a keyboard
/*
Chrome does not let you modify the keyCode prop when you trigger it, so it defaults to 0.
You can use this code to trigger a keydown with a char code of 0 in chrome.
If you use initKeyEvent instead of initKeyboardEvent, it will work in FF
(the bellow example would trigger keydown with a char code of 65 in FF).
*/
document.addEventListener( 'keydown', function( event ){
console.log( event.keyCode )
}, false);
var event = document.createEvent( 'KeyboardEvent' );
event.initKeyboardEvent( 'keydown', true, false, null, 0, false, 0, false, 65, 0 );
document.dispatchEvent( event );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment