amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

creating-keyboard-shortcuts-combination-keys-javascript/ #7

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Creating Keyboard shortcuts of combination of keys in JavaScript – Amit Merchant – A blog on PHP, JavaScript and more

Recently, I added a set of few keyboard shortcuts on this blog which helps in navigating through different parts of the blog conveniently. You can check all the shortcuts on this dedicated page.

https://www.amitmerchant.com/creating-keyboard-shortcuts-combination-keys-javascript/

zakius commented 3 years ago

I have something a bit more generic with

let shortcut = '';
if (event.ctrlKey) {
    shortcut += 'ctrl+';
}
if (event.altKey) {
    shortcut += 'alt+';
}
if (event.shiftKey) {
    shortcut += 'shift+';
}

if (event.keyCode > 46 && event.keyCode < 91) {
    shortcut += String.fromCharCode(event.keyCode).toLowerCase();
} else if (event.keyCode in shortcuts.keys) {
    shortcut += shortcuts.keys[event.keyCode];
} else {
    return;
}

where shortcuts.keys maps some codes in range 8-46 to names and shortcuts are saved in mapping of shortcutLiteral: actionName like

shortucts.mappings = 
{
  'ctrl+d': 'delete',
  'del': 'delete',
  'ctrl+f': 'find',
}

it's a good base to make it configurable

of course it probably needs some cleanup, but it works

amitmerchant1990 commented 3 years ago

@zakius Yes. This can prove to be useful when you have to setup a lot of shortcuts. It's more maintainable.