Created
August 26, 2014 11:52
-
-
Save lsauer/0fe1f848abc9931735f2 to your computer and use it in GitHub Desktop.
JavaScript: Simulate Keyboard Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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