Skip to content

Instantly share code, notes, and snippets.

@va9iff
Last active July 8, 2024 14:57
Show Gist options
  • Save va9iff/30f77e0cbe9475c3be3caa2bd3dd545b to your computer and use it in GitHub Desktop.
Save va9iff/30f77e0cbe9475c3be3caa2bd3dd545b to your computer and use it in GitHub Desktop.
elegant JavaScript keyboard shortcut binder
(() => {
function makeBindi(keys) {
return new Proxy({}, {
get(_, key) {
return makeBindi([...keys, key])
},
set(_, key, func) {
document.addEventListener('keydown', e => {
if (
(e.key.toLowerCase() === key) &&
(keys.includes("alt") ? e.altKey : true) &&
(keys.includes("shift") ? e.shiftKey : true) &&
(keys.includes("ctrl") ? e.ctrlKey : true)
) func(e)
})
return true
},
})
}
window.bindi = new Proxy({}, {
get(_, key) {
return makeBindi([key])
},
})
})()
window.bindi.ctrl.shift.v = e => alert("hii")
window.bindi.ctrl.y = e => alert("yanked it")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment