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?
Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
Keycode 13 is the Enter key.
There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.
The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .
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');
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With