0

I made a simple JS fiddle that listens for key down and up events:

window.document.addEventListener('keypress', function(e) {
    e.preventDefault();
    console.log(e);
    return false;
});

window.document.addEventListener('keyup', function(e) {
    e.preventDefault();
    console.log(e);
    return false;
});

When I press down on a letter, the key code logged is 32 greater than the key code logged while pressing up. Why is that?

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • Because key handling (as opposed to an actual *letter* being typed) in JavaScript is .. fun. Basically mapped from *arbitrary virtual key codes* (who defined these back in the day?). YMMV; the values are just what they are. – user2864740 May 10 '15 at 23:09
  • I think it is fairly arbitrary. Somebody way back when in like the 1900s (gasp) just decided that the up arrow should be before the down arrow. – Sumner Evans May 10 '15 at 23:09
  • @jsve The question is not about the ordering. If you press on a key, and then depress that same key, 2 different key codes are logged. – chiliNUT May 10 '15 at 23:11
  • Keyup is case insensitive. Keypress is case sensitive. Also explained and demonstrated here - http://howtodoinjava.com/2013/12/20/jquery-difference-between-keypress-and-keydown-events/ – tmrlvi May 10 '15 at 23:13
  • @tmrlvi wow. thats rediculous. – chiliNUT May 10 '15 at 23:14
  • 1
    Are you talking about `which`, `charCode`, `code`, `keyCode`, ...? Detecting keys in JS is a mess. And the `keypress` event is deprecated. – Oriol May 10 '15 at 23:14
  • @Oriol where have you read that the `keypress` event is deprecated? – Norman Breau May 10 '15 at 23:19
  • 1
    @NormanBreau [DOM L3 Events](http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress): "*The `keypress` event type is defined in this specification for reference and completeness, but this specification [deprecates](http://www.w3.org/TR/DOM-Level-3-Events/#glossary-deprecates) the use of this event type.*" – Oriol May 10 '15 at 23:22
  • You are comparing apples and oranges. The `keydown` and `keyup` events are triggered by pressing and releasing keys. The code reported represents the key. The `keypress` event is triggered when pressing or holding a key (repeating) results in a character input. The code reported represents the character. – Guffa May 10 '15 at 23:26

0 Answers0