Search code examples
javascriptkeypress

Detecting multiple key press at once and don't response when other keys are pressed


I have an admin panel, and I want to set a keyboard shortcut that redirects the user to this panel when he presses {A+D+M+N} all at the same time.

I have this code:

document.onkeypress = function (e) {
    e = e || window.event;
    // use e.keyCode
};

But it works only for one key press, it doesn't work for multiple key detection.

Also, I wont to detect (A+D+M+N) only, and if user pressed all the buttons on the keyboard, or (A+D+M+N+X+Z) for example, it should not response.

Any ideas or frameworks to implement that?


Solution

  • keyPressListener, is a library that I've developed for that matter.

    Firstly, since you want to match only your preferred keys without any other keys, then make sure to set ignoreOtherInput to false:

    keyPressListener.config({ignoreOtherInput: false});
    

    Secondly, now you can call the listener function:

    keyPressListener.when('A+D+M+N', function(){
      window.location.href = '/admin-panel'; // If user pressed (A+D+M+N), go to admin panel
    });
    

    So if the user pressed (A+D+M+N) it will redirect him to the admin panel and if he pressed all the buttons on the keyboard, or (Ctrl+A+D+M+N) for example, it won't response.

    More: @https://github.com/RyadPasha/keyPressListener