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?

1
  • keyup is fired when a key is released use keydown to fire an event when a key is pressed Commented Dec 20, 2011 at 10:16

4 Answers 4

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');
   }
})
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
4
$('input').keyup(function (e){
    alert("You pressed the \"Any\"-key.");
})

Comments

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().

Comments

1
$("input").keypress(function() {
  alert("hello.");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.