1

I've been trying to get jQuery to detect a number of letters entered after each other on a keyboard.

Actually, all I wanted to achieve is, to use the .keypress function to detect a word instead of a single character. Now, I can't type a word and press all keys at the same time, so I have to program a way where jQuery remembers the letters I've typed in before, so if I write "test", it will remember "t,e and s" before I type in the last "t" which will then make a if condition come true.

Here's what I tried, but I don't know how to store characters (basically like a keylogger, but simply for a single word, which will be used to open an application):

$(document).keypress(function(e) {
  if( e.ctrlKey && ( e.which === 46 ) ) {
    alert('Ctrl and DEL pressed!');
  }
});

This way, I managed to get jQuery recognize a key combination, but that's all I know for now.

Can anyone help me to figure out how to detect a whole world?

Thank you so much.

DerGoliHerr
  • 94
  • 10
  • 2
    How are you defining a word? Would looking for a space character work? – TheNorthWes May 29 '14 at 16:45
  • The application is kind of like a "help center", so the simplest word to be detected would be "help". There doesn't need to be a space involved :) – DerGoliHerr May 29 '14 at 16:47
  • So you have a white list of words you are looking for? – TheNorthWes May 29 '14 at 16:48
  • not yet, I thought it could be done like in the example above. Example: ( e.which === 46 ) && ( e.which === 55 ) && ( e.which === 99 ) and so on (but that will only allow me to press all keys at the same time) – DerGoliHerr May 29 '14 at 16:49

1 Answers1

2

Based on your comments:

I think the best way to go about this would be to grab the text and check if it contains an item in your whitelist.

Otherwise if you user copy pastes, or moves to another input, you could miss some characters. I also would hesitate to do this on keyup but depends on your whitelist etc.

Something like this could work.

$( "#target" ).keyup(function() {

     var inputText = $( "#target" ).text();
     whitelist.forEach(function(){
          if(inputText.indexOf(aWhiteListItem) > 0)
          {
              alert("Found it");
          }
     });
  });

If you are curious about waiting for a delay, there are lots of great SO posts

Community
  • 1
  • 1
TheNorthWes
  • 2,661
  • 19
  • 35
  • Thank you, worked very well, just had to adapt it a bit, since I wanted to use it on the complete body (anywhere on the site, without having to focus, or linked to an input) :) – DerGoliHerr May 29 '14 at 17:44