Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
Cyril F Avatar asked May 31 '12 20:05

Cyril F


People also ask

Should I use Keyup or Keydown?

There is no such best practice. Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.

What is Keyup and Keydown in jquery?

Definition and Usagekeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.


2 Answers

You can combine them like this:

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

   } else {
      // it is keypress
   }
});
like image 94
lucuma Avatar answered Sep 20 '22 19:09

lucuma


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

like image 43
Tooraj Jam Avatar answered Sep 20 '22 19:09

Tooraj Jam