Combine keypress and keyup - jQuery
Asked Answered
J

3

8

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.

Jacquie answered 31/5, 2012 at 20:18 Comment(5)
Are they entering this phrase inside an input? Also you mention your problem is comparing strings of different cases and then you are asking about keypress and keyup?Suntan
No. It's a plugin to do like a "konami code" but with the password of your choice. I'm comparing the first string (key-phrase) with the user inputJacquie
I think I'm too old to know what konomi code is however I have provided you an answer about combining both the events..Suntan
You can have a try here : konamicodesites.com Press the following keys : "Up / Up / Down / Down / Left / Right / Left / Right / B / A"Jacquie
Ok, I get it now, just didn't know the name.. Reminds me of commando from back in the day. +1 for teaching me that one!Suntan
S
15

You can combine them like this:

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

   } else {
      // it is keypress
   }
});
Suntan answered 31/5, 2012 at 20:31 Comment(2)
Consequently you can easily compare strings by s.toUpperCase() == t.toUpperCase()Suntan
Your answer will help me. Thanks. (I don't want to use upperCase for the comparaison because I want to keep this information)Jacquie
M
2

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

Mazman answered 31/5, 2012 at 20:33 Comment(0)
L
0

You can use oninput event instance keyup keydown:


JQuery:

$(input).input(function(){ ...

javascript:

input.addEventListener("input", function (event) { ...
Luvenialuwana answered 25/6 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.