5

i know that i can detect a key, which has been pressed with the following code:

$('input').keyup(function (e){
if(e.keyCode == 13){
    alert('enter');
  }
})

But i need to know if any key was pressed. pseudocode:

if ($('input').keyup() == true)
  { 
      doNothing();
  }
  else {
      doSomething();
  }

How can I do that?

Keith L.
  • 2,084
  • 11
  • 41
  • 64

4 Answers4

9

Because 'keyup' will be fired when ANY key is pressed, you just leave out the if...

$('input').keyup(function (e){
  // do something
})

Merging this into your current code, you could do something like...

$('input').keyup(function (e){
  alert('a key was press');

  if (e.keyCode == 13) {
      alert('and that key just so happened to be enter');
   }
})
isNaN1247
  • 17,793
  • 12
  • 71
  • 118
  • but i need the "else" part, if a key is not pressed. I have to handle not only the "you pressed a key" part, but also the "you pressed no key" part. – Keith L. Dec 20 '11 at 10:14
  • 3
    How on earth should you determine that the user didn't press a key? The absence of the .keyup() event firing means that the user currently isn't releasing a key. – Andreas Eriksson Dec 20 '11 at 10:18
4
$('input').keyup(function (e){
    alert("You pressed the \"Any\"-key.");
})
Andreas Eriksson
  • 8,979
  • 8
  • 47
  • 65
2

If you want to check if the user didn't press a key you could use a setInterval() function.

var interval = setInterval(function() {
    //Do this if no key was pressed.
}, 2000);

Note that you should clear the interval as well clearInterval().

Filip
  • 2,514
  • 17
  • 28
1
$("input").keypress(function() {
  alert("hello.");
});
sascha
  • 4,671
  • 3
  • 36
  • 54