jquerykeypresskeydownkeyup

Combine keypress and keyup - jQuery


I'm trying to develop a jQuery plugin to do an action when the user enter a specific keyphrase.

For example, I want to match "HELLO" on keyup.

var controllerKey = [];
$(window).keyup(function(evt) {
    var code = evt.keyCode ? evt.keyCode : evt.which;
    controllerKey.push(code);
}
[...]

Then, I compare my controllerKey with my string "HELLO" (thanks to str.charCodeAt()) and some others things but this isn't important here. Everything works fine at this point.

My problem happens when I want to match "HeLLo" (in fact when the string had some uppercase). I saw on forums that keyup or keydown don't make any difference.

So I use keypress which manage it very well but keypress doesn't allow me to match arrow keys and so one (in Chrome).

I want to know if it's possible to combine keypress and keyup (only when keypress doesn't match the event).

Thanks in advance.


Solution

  • You can combine them like this:

    $(window).on('keyup keypress', function(e) {
       if (e.type=="keyup") {
    
       } else {
          // it is keypress
       }
    });