Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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

This comment has been minimized.

Copy link

@ajpen ajpen commented Jan 1, 2015

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

@Litmind-zz

This comment has been minimized.

Copy link

@Litmind-zz Litmind-zz commented Nov 16, 2016

el is indeed an element ajpen

@yanlee26

This comment has been minimized.

Copy link

@yanlee26 yanlee26 commented Nov 3, 2017

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

@VolodymyrPliuta

This comment has been minimized.

Copy link

@VolodymyrPliuta VolodymyrPliuta commented Aug 1, 2019

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