Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function for simulating key event in JavaScript. You just have to choose what key and keyboard event you want to simulate.
/**
* Simulate a key event.
* @param {Number} keyCode The keyCode of the key to simulate
* @param {String} type (optional) The type of event : down, up or press. The default is down
* @param {Object} modifiers (optional) An object which contains modifiers keys { ctrlKey: true, altKey: false, ...}
*/
function simulateKey (keyCode, type, modifiers) {
var evtName = (typeof(type) === "string") ? "key" + type : "keydown";
var modifier = (typeof(modifiers) === "object") ? modifier : {};
var event = document.createEvent("HTMLEvents");
event.initEvent(evtName, true, false);
event.keyCode = keyCode;
for (var i in modifiers) {
event[i] = modifiers[i];
}
document.dispatchEvent(event);
}
// Setup some tests
var onKeyEvent = function (event) {
var state = "pressed";
if (event.type !== "keypress") {
state = event.type.replace("key", "");
}
console.log("Key with keyCode " + event.keyCode + " is " + state);
};
document.addEventListener("keypress", onKeyEvent, false);
document.addEventListener("keydown", onKeyEvent, false);
document.addEventListener("keyup", onKeyEvent, false);
// Using the function
simulateKey(38);
simulateKey(38, "up");
simulateKey(45, "press");
@uaoleg
Copy link

uaoleg commented Jun 3, 2021

That was super helpful! Thank you!

@b31ngd3v
Copy link

b31ngd3v commented Jun 16, 2021

Thanks @GlauberF

@artursobon
Copy link

artursobon commented Jun 18, 2021

Pretty nice! Thx!

@DemonLordDiablo
Copy link

DemonLordDiablo commented Sep 15, 2021

can i use this to make alt key forever down, and if so how?

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