Skip to content

Instantly share code, notes, and snippets.

@lsauer
Created August 26, 2014 11:52
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 lsauer/0fe1f848abc9931735f2 to your computer and use it in GitHub Desktop.
Save lsauer/0fe1f848abc9931735f2 to your computer and use it in GitHub Desktop.
JavaScript: Simulate Keyboard Events
//lsauer.com, 2012; rev. 2014 by lo sauer
//see also: http://stackoverflow.com/questions/596481/simulate-javascript-key-events/19883789#19883789
//description: trigger handlers attached to DOM elements, which listen to the type 'KeyboardEvent'
//@param s: A single keyboard-character passed as a string e.g. "\n", "a",...
//[@param fncb]:callback function which is passed a boolean event-state (OK=true/Cancelled=false)
var doKeyEvent = function(s /*single char*/, fncb /*callback function, with handler state*/) {
var evt = document.createEvent('KeyboardEvent');
evt.initKeyEvent ('keypress', true, true, window,0, 0, 0, 0, 0, s.charCodeAt(0))
var cncld = !document.getElementsByTagName('body')[0].dispatchEvent(evt);
if(!fncb || typeof fncb != 'function'){
fncb = function(b){if(b) { console.log('event cancelled/preventDefault-ed');} else {console.log(evt, 'received');}};
}
fncb.call(this, !cncld);
}
@jslegers
Copy link

initKeyEvent has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/initKeyEvent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment