3

I am writing a simple function in jQuery. When I hit the 1 key on my keyboard it hides my documents. This works fine:

document.onkeypress=key1;

function key1(e) {
  if (e.which == 49) {
    // alert("testing");
    $("#documentViewer").hide();
  }
}

Now the problem occurs when instead of pressing 1, I want this function to work on print screen (keycode 44) or Windows key (keycode 91/92) when I pressed them.

I tried including changing the keycode to these values and sadly, it doesn't hide the document or even throw an alert call. It couldn't detect the key press.

I even used this link below to check what is the keycode when I pressed a key: https://keycode.info/

Pressing printscreen or win keys does not give me any value at all. I do not know why. Is there anything I am doing wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Daredevil
  • 1,672
  • 3
  • 18
  • 47
  • Those wondering about the difference between `keypress` and `keyup` events. Here is the StackOverflow [link](https://stackoverflow.com/q/3396754/3048967). – ScrapCode Feb 18 '19 at 10:02

1 Answers1

4

The issue is because the keypress event does not fire for key presses which do not create printable content.

The workaround is to use keyup instead:

document.onkeyup = key1;

function key1(e) {
  switch (e.which) {
    case 49: // 1
      $("#documentViewer").hide();
      break;
    case 44: // PrintScreen
      console.log('You pressed print screen');
      break;
    case 91: // left windows
    case 92: // right windows
      console.log('You pressed the one of the windows keys');
      break;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="documentViewer">Foo</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339