Created
August 29, 2012 21:52
-
-
Save callmephilip/3519403 to your computer and use it in GitHub Desktop.
[JavaScript] Dispatching keyboard event
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
// gecko and webkit | |
// details here https://developer.mozilla.org/en-US/docs/DOM/event.initKeyEvent | |
var keyboardEvent = document.createEvent("KeyboardEvent"); | |
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent"; | |
keyboardEvent[initMethod]( | |
"keydown", // event type : keydown, keyup, keypress | |
true, // bubbles | |
true, // cancelable | |
window, // viewArg: should be window | |
false, // ctrlKeyArg | |
false, // altKeyArg | |
false, // shiftKeyArg | |
false, // metaKeyArg | |
40, // keyCodeArg : unsigned long the virtual key code, else 0 | |
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0 | |
); | |
document.dispatchEvent(keyboardEvent); | |
/* a better way */ | |
function fireKey(el,key) | |
{ | |
if(document.createEventObject) | |
{ | |
var eventObj = document.createEventObject(); | |
eventObj.keyCode = key; | |
el.fireEvent("onkeydown", eventObj); | |
eventObj.keyCode = key; | |
}else if(document.createEvent) | |
{ | |
var eventObj = document.createEvent("Events"); | |
eventObj.initEvent("keydown", true, true); | |
eventObj.which = key; | |
eventObj.keyCode = key; | |
el.dispatchEvent(eventObj); | |
} | |
} | |
//useful keyCodes | |
// left: 37 | |
// up : 38 | |
// right : 39 | |
// down : 40 | |
// ENTER : 13 |
el is indeed an element ajpen
can this , which only use native js , mock up auto type by the keyboard?
link form line 2 is broken https://developer.mozilla.org/en-US/docs/DOM/event.initKeyEvent
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is the purpose of el, in the second function? Does it refer to the element?