Search code examples
javascriptdom-eventskeypresskeydownkeycode

Keydown and keypress events gives different keyCode


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 ?


Solution

  • 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.