Objective: Listen for key press events to catch printable characters.
Problem: keyPress, the perfect solution for this issue, is deprecated and not recommended anymore, and the alternative keyDown doesn't produce the same key and code values as keyPress for printable characters, and it's also inconsistent with it self across browsers.
Reproduce: If you wish to attempt reproducing the issue, use this website different browsers and compare your results
Example: when pressing ; on keyboard:
| Event | key | code | which | charCode |
|---|---|---|---|---|
| keyDown | . | 190 | 0 | 0 |
| keyPress | ; | 59 | 59 | 59 |
| keyUp | . | 190 | 0 | 0 |
| Event | key | code | which | charCode |
|---|---|---|---|---|
| keyDown | ; | 59 | 59 | 59 |
| keyPress | ; | 59 | 59 | 59 |
| keyUp | ; | 59 | 59 | 59 |
Current Solution: I'm using keyDown and allowing only key values that match a RegEx to be processed.
Note: I'm using a keyboard with 2 languages, but I don't think this is should interfere with anything, since keyPress works fine.
Question: How can I get keyDown to produce same correct keyCode values that keyPress produces across browsers? Or should I just use keyPress dispite it being not recommended anymore.
EDIT: You may want to check out 3.3. Key Code Values of this clever and well detailed article about this problem to better understand this issue
See MDN:
KeyboardEvent.keyCode
Deprecated: This feature is no longer recommended.
and
You should avoid using this if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code,
const kbd = document.querySelector('kbd');
document.querySelector('input').addEventListener('keydown', e => {
kbd.innerText = e.code;
});
<input>
<kbd></kbd>