Search code examples
jqueryuserscripts

Can all keycode events be recognized by a user-script Jquery


I am building a userscript with Tampermonkey that recognizes keycode events and when the key is fired it will do a function.

for eg. I want to press Enter and its keycode is 13 so I used this code

$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
    alert("You Pressed Enter key");
}
else if(which == '17'){
    alert("You Pressed Control key");
}
});

The code works fine with Enter and with 1 but doesn't work with Ctrl nor Shift and other keys.

Is there any thing I am missing or not all key events can be handled?

NOTE : I have been using this link to get my keycodes and using them in my script.


Solution

  • keypress isn't triggered for control key. Per the description on Mozilla docs:

    The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

    One way to get around is to listen to keydown or keyup event:

    $(document).keydown(function(event) {
      var which = (event.which ? event.which : event.keyCode);
      if (which == '13') {
        alert("You Pressed Enter key");
      } else if (which == '17') {
        alert("You Pressed Control key");
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>