Just for background, the "keypress" event will give you a charCode property whenever you press a character key.
Editor.addEventListener('keypress', function(event){
if (event.charCode) {
//// character key
console.log( String.fromCharCode(event.charCode) ); /// convert charCode to intended character.
} else {
//// control key
}
However, the "keypress" event doesn't capture every keystroke - several keys fire before the "keypress" event.
In contrast, the "keydown" event will capture every keystroke, but it doesn't have a charCode property. So how can we tell if it's a character key? Checking on every key stroke whether the keyCode is within the lower and upper bounds for multiple ranges isn't optimally efficient. I suspect that there are also issues for characters outside of the ASCII range.
My approach is the check the length of the event "key" property. The "key" property is an alternative to "keyCode" to determine which key was pressed. For control keys, the "key" property is descriptive (e.g. "rightArrow", "F12", "return", etc.). For character keys, the "key" property for a character key is just the character (e.g "a", "A", "~", "\", etc.). Therefore, for every character key, the length of the "key" property will have length of 1; whereas control characters will have length greater than 1.
Editor.addEventListener('keydown', function(event){
if (event.key.length == 1){
//// character key
} else {
//// control key
}
})
keyCode
is system and implementation-dependent, which only traduces to problems – Patriliny