Skip to content

Instantly share code, notes, and snippets.

@lcssanches
Last active August 24, 2020 06:44
Show Gist options
  • Save lcssanches/08ac9ccd7af0f38930c1d0f96bb775ad to your computer and use it in GitHub Desktop.
Save lcssanches/08ac9ccd7af0f38930c1d0f96bb775ad to your computer and use it in GitHub Desktop.
Vanilla Javascript Shortcut mapping
/*
Include this file inside your HEAD tag and add the attribute
`shortcut-key` (or `shortcut-keys`) to any HTML element that accepts .click().
<button shortcut-keys="enter,space">Submit</button>
This code use KeyboardEvent.code to map the shortcuts. See more https://developer.mozilla.org/pt-BR/docs/Web/API/KeyboardEvent/code
*/
(function (d) {
const keyMapping = {};
d.addEventListener("DOMContentLoaded", function () {
const elements = d.querySelectorAll("[shortcut-key], [shortcut-keys]");
elements.forEach(function (elem) {
const keys = elem.getAttribute("shortcut-key") || elem.getAttribute("shortcut-keys");
keys.split(",").forEach(function (key) {
if (keyMapping[key]) {
throw new Error(`Double mapping found for key {${key}}.`)
}
keyMapping[key.toLowerCase()] = function () {
elem.click()
};
})
})
});
d.onkeydown = function ({code}) {
if (!keyMapping[code.toLowerCase()])
return;
keyMapping[code.toLowerCase()]();
}
})(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment