JQuery: if "someKey" key is pressed

I know that I can detect a key that was pressed with the following code:

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

But I need to know if a key has been pressed. pseudo code:

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

How can i do this?

+4
source share
4 answers

Since "keyup" will be triggered when the ANY key is pressed, you simply will not specify if ...

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

By combining this in your current code, you can 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'); } }) 
+7
source
 $('input').keyup(function (e){ alert("You pressed the \"Any\"-key."); }) 
+4
source

If you want to check if the user has pressed a key, you can use the setInterval () function.

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

Note that you must also clear the clearInterval() interval.

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

Source: https://habr.com/ru/post/1387174/


All Articles