Combine keypress and keyup - jQuery

16,646

Solution 1

You can combine them like this:

$(window).on('keyup keypress', function(e) {
   if (e.type=="keyup") {

   } else {
      // it is keypress
   }
});

Solution 2

You can use a hidden input and key events in order to have cross browser case sensitive compare.

Share:
16,646
Cyril F
Author by

Cyril F

Traveler and web developer. Nomad. Really, no mad!

Updated on June 16, 2022

Comments

  • Cyril F
    Cyril F almost 2 years

    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.