0

I've read through related answers and articles on Stack Overflow, but still doesn't get it:

On Chrome console if I add two listeners to output keyCode on keypress and keydown events I get different keycode when the key is lowercase.

When uppercase however, the keyCode appears to be the same for the two events.

Example:

document.addEventListener('keypress', function(e){ console.log('keyPress', e.keyCode); });
document.addEventListener('keydown', function(e){ console.log('keyDown', e.keyCode); });

// Open your console  
// Typing 'a' in the result field outputs 'keyPress 97' 'keyDown 65'
// on chrome 42 console. Activate uppercase, and then typing 'A' outputs 'keyPress 65' and 'keyDown 65'

// Why ? 

So is this normal behaviour ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
lkostka
  • 711
  • 1
  • 5
  • 10
  • IRRC keypress isn't raised by all keys, keydown is. Also I think keycode differ between browsers. – garryp Apr 26 '15 at 00:09
  • It is normal, that's why there are different events, because they behave differently. "The keypress event is fired when a key is pressed down and that key normally produces a character value" -- https://developer.mozilla.org/en-US/docs/Web/Events/keypress – elclanrs Apr 26 '15 at 00:09
  • http://stackoverflow.com/questions/1367700/whats-the-difference-between-keydown-and-keypress-in-net explains it well. – Shawn Jacobson Apr 26 '15 at 00:14
  • Thanks for fast commenting ! Yes I understand they are different events, but the key is the same. That is proved in addition when looking at upperCase behaviour : the keycode appears to be identical. – lkostka Apr 26 '15 at 00:14
  • @ShawnJacobson Thanks for the great article, I understand that keypress occurs after keydown, before input and before keyup. I am just wondering why the keyCode differs between the two when lowercase but not when uppercase. – lkostka Apr 26 '15 at 00:19
  • Because keydown is only tracking the key itself, not the state of the key. If you press 'A' KeyDown generates a KeyCode of Keys.A and if you press 'shift-A' you also get a KeyCode of Keys.A. – Shawn Jacobson Apr 26 '15 at 00:22
  • @ShawnJacobson ok I got it, sorry for being low to understand, the word state solved everything. If you want to answer I'll accept it – lkostka Apr 26 '15 at 00:27
  • Does this answer your question? [What's the difference between KeyDown and KeyPress in .NET?](https://stackoverflow.com/questions/1367700/whats-the-difference-between-keydown-and-keypress-in-net) – Brian Tompsett - 汤莱恩 May 29 '20 at 18:00

1 Answers1

0

What's the difference between KeyDown and KeyPress in .NET?… explains it well. keydown is only tracking the key itself, not the state of the key. If you press A KeyDown generates a KeyCode of Keys.A and if you press shift+A you also get a KeyCode of Keys.A.

Community
  • 1
  • 1
Shawn Jacobson
  • 1,352
  • 8
  • 13