jQuery: if key "someKey" pressed

Keith L. picture Keith L. · Dec 20, 2011 · Viewed 10.9k times · Source

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?

Answer

isNaN1247 picture isNaN1247 · Dec 20, 2011

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');
   }
})