jaywcjlove / hotkeys-js

➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
https://jaywcjlove.github.io/hotkeys-js
MIT License
6.63k stars 407 forks source link

Restore default filter (hotkeys disabled in input, textarea and selects) #321

Open Haytam95 opened 3 years ago

Haytam95 commented 3 years ago

Hi! I'm using:

hotkeys.filter = function(event){
  return true;
}

To enable hotkeys during certain forms.

When I exit those forms, I would like to restore the default filter to avoid triggering hotkeys when the user is on a input, textarea or select.

How can I do that? Is there some function to restore the custom functionality or I should rewrite hotkeys.filter checking the element that has focus?

Thanks

chrisvidal commented 2 years ago

did you find a solution?

Haytam95 commented 2 years ago

Yes, extracted from the source code:

public static defaultHotkeysFilter = function (event) {
        // hotkey is effective only when filter return true
        const target = event.target || event.srcElement;
        const {tagName} = target;
        let flag = true;
        // ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
        if (target.isContentEditable || ((tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly)) {
            flag = false;
        }
        return flag;
    };

(For javascript just replace public static with const)

Here is the usage:

const hotkeys = require('/src/assets/js/hotkeys');

hotkeys.filter = defaultHotkeysFilter;