char
is deprecatedcharCode
is deprecatedkey
fires for both printable characters and control keyskeyCode
is deprecatedwhich
is deprecatedkeypress
is deprecatedinput
does not fire for elements that are notinput
,textarea
,select
orcontenteditable
- most annoyinglytabindex
is not enough
Is the remended way going forwards to keep the list of predefined key
values as a blacklist and assume what's not on there is a printable character? How's that going to work out for keyboards with special/programmable keys?
When trying to capture printable characters on non-input|textarea|select|contenteditable
, is as of current the only non-hacky (no inplete ranges or blacklists as seen in many similar questions) way without using deprecated features to use a hidden input
/textarea
and use its value for capturing characters that actually change that value?
char
is deprecatedcharCode
is deprecatedkey
fires for both printable characters and control keyskeyCode
is deprecatedwhich
is deprecatedkeypress
is deprecatedinput
does not fire for elements that are notinput
,textarea
,select
orcontenteditable
- most annoyinglytabindex
is not enough
Is the remended way going forwards to keep the list of predefined key
values as a blacklist and assume what's not on there is a printable character? How's that going to work out for keyboards with special/programmable keys?
When trying to capture printable characters on non-input|textarea|select|contenteditable
, is as of current the only non-hacky (no inplete ranges or blacklists as seen in many similar questions) way without using deprecated features to use a hidden input
/textarea
and use its value for capturing characters that actually change that value?
2 Answers
Reset to default 4Okay after looking into it for some time, the answer is: You can't determine this without relying on deprecated APIs or textarea
hack.
Of course these are unlikely to ever go away, but if someone ends up looking for a way to do this without them, they won't find one.
A partial solution is a blacklist of the key
values, but it's only a question of a new TV ing out with a quirky remote with extra proprietary keys or something like that and all bets are off.
As a pragmatic solution use key
:
- assume that all single-character key names are printable
- currently true except for space:
" "
- https://developer.mozilla/en/docs/Web/API/KeyboardEvent/key/Key_Values
- currently true except for space:
- check that no modifiers were pressed (https://stackoverflow./a/4194212)
Example code:
const isPrintableChar = e.key.length === 1 && e.key !== ' ';
const noModifier = !e.ctrlKey && !e.metaKey && !e.altKey;
return isPrintableChar && !noModifier;
For backward patibility, consider using e.which
as a fallback.