4

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.

Bak Stak
  • 127
  • 3
  • 16
Joe
  • 879
  • 3
  • 14
  • 37

2 Answers2

4

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>
31piy
  • 23,323
  • 6
  • 47
  • 67
1

To determine left and right ctrl, alt, and shift keys also :

$(document).keyup(function (e) {
      if (e.keyCode == 16) {
          if (e.originalEvent.location == 1)
              alert('Left SHIFT pressed.');
          else
              alert('Right SHIFT pressed.');
      } else if (e.keyCode == 17) {
          if (e.originalEvent.location == 1)
              alert('Left CTRL pressed.');
          else
              alert('Right CTRL pressed.');
      } else if (e.keyCode == 18) {
          if (e.originalEvent.location == 1)
              alert('Left ALT pressed.');
          else
              alert('Right ALT pressed.');
          e.preventDefault();
      }
});

You have to include jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Joe
  • 879
  • 3
  • 14
  • 37
Md. Khairul Hasan
  • 704
  • 1
  • 10
  • 21