hotkey
hotkey copied to clipboard
Any ways to define which event to fire when hotkey is triggered?
Hey fine folks! I've been using hotkey
for a couple of weeks, it's very cool, thanks a lot for the work you put into this already 🙏🏽
I was wondering if there were any possibilities to define a custom event to fire when the hotkey is pressed by the user?
My example: I setup a hotkey onto a select
element, and did hope for the select element to be opened on hotkey press. Unfortunately, because of how the fireDeterminedAction
function is defined, it only focuses on the select
, which I need to then trigger to open by navigating with arrow keys, for instance.
Would it be something useful to add to the library, or sth to prevent developers from doing for specific reasons I don't grasp yet?
Either way, thanks for taking the time to read this!
I just stumbled upon this merged PR, introducing a custom hotkey-fire
event. Would it be the way to go at this? If it is, it could be nice to get it documented somehow?
Yeah the hotkey-fire event is used to provide custom behaviours other than clicking links and buttons.
Sorry we didn’t fully document that! Would you like to make a PR documenting it? That would be an awesome improvement!
Yeah, it'd be really great to get some documentation on this - it seems like it would be a fairly common use? Having found the library today, that was the first thing I went looking for.
I've added some documentation to the README: https://github.com/github/hotkey/blob/main/README.md#js
By default form elements (such as input,textarea,select) or elements with contenteditable will call focus() when the hotkey is triggered. All other elements trigger a click(). All elements, regardless of type, will emit a cancellable hotkey-fire event, so you can customize the behaviour, if you so choose:
for (const el of document.querySelectorAll('[data-shortcut]')) { install(el, el.dataset.shortcut) if (el.matches('.frobber')) { el.addEventListener('hotkey-fire', event => { // ensure the default `focus()`/`click()` is prevented: event.preventDefault() // Use a custom behaviour instead frobulateFrobber(event.target) }) } }
I'll close this for now as I think this is effectively solved. Let me know if you have any other questions or find any other issues and I'll be happy to help :slightly_smiling_face: