Skip to content

Instantly share code, notes, and snippets.

@sirbaconjr
Last active February 11, 2019 05:29
Show Gist options
  • Save sirbaconjr/24012ffda68387417d7214ce9c74617f to your computer and use it in GitHub Desktop.
Save sirbaconjr/24012ffda68387417d7214ce9c74617f to your computer and use it in GitHub Desktop.
This is a JS function to record keyboard input and process callback for specific key combinations. If you see a problem or know how to make it better, please contact me.
function getEventCode(event) {
if (event.key !== undefined) {
return event.key;
}
if (event.keyIdentifier !== undefined) {
return event.keyIdentifier;
}
if (event.keyCode !== undefined) {
return event.keyCode;
}
return undefined;
}
function setupKeyCodeHandler() {
if (window.keyStack === undefined) {
window.keyStack = new Map();
window.keyStack.callbacks = new Map();
window.keyStack.on = function(command, callback) {
if (typeof command !== "string" || typeof callback !== "function") {
throw new Error("The first parameter must be a string and the second must be a callback");
}
var cbs = window.keyStack.callbacks.get(command);
if (cbs === undefined) {
cbs = [];
}
cbs.push(callback);
window.keyStack.callbacks.set(command, cbs);
};
window.keyStack.check = function() {
propagate = true;
window.keyStack.callbacks.forEach((cbs, command) => {
var commands = command.split(" ");
var execute = 0;
for (let c of commands) {
if (window.keyStack.get(c)) {
execute++;
}
}
if (commands.length > 0 && execute === commands.length) {
for (let cb of cbs) {
propagate = propagate && cb();
}
}
});
return propagate;
};
document.onkeyup = function(e) {
keyCode = getEventCode(e);
if (keyCode === undefined) {
return true;
}
window.keyStack.set(keyCode.toLowerCase(), false);
return window.keyStack.check();
};
document.onkeydown = function(e) {
keyCode = getEventCode(e);
if (keyCode === undefined) {
return true;
}
window.keyStack.set(keyCode.toLowerCase(), true);
return window.keyStack.check();
};
return true;
}
return false;
}
//Usage
setupKeyCodeHandler(); //setup keyCodeHandler, returns true if ok, returns false if already set
window.keyStack.on('control e', () => {
console.log("Ctrl + E");
return false;//key combinations that are used by the browser must return false to prevent default browser action
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment