Skip to content

Instantly share code, notes, and snippets.

@callmephilip
Created August 29, 2012 21:52
Show Gist options
  • Save callmephilip/3519403 to your computer and use it in GitHub Desktop.
Save callmephilip/3519403 to your computer and use it in GitHub Desktop.
[JavaScript] Dispatching keyboard event
// 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
@ajpen
Copy link

ajpen commented Jan 1, 2015

What is the purpose of el, in the second function? Does it refer to the element?

@Litmind-zz
Copy link

el is indeed an element ajpen

@yanlee26
Copy link

yanlee26 commented Nov 3, 2017

can this , which only use native js , mock up auto type by the keyboard?

@VolodymyrPliuta
Copy link

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