Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if key press resulted in printable Unicode character being input without deprecated APIs

  • char is deprecated
  • charCode is deprecated
  • key fires for both printable characters and control keys
  • keyCode is deprecated
  • which is deprecated
  • keypress is deprecated
  • input does not fire for elements that are not input, textarea, select or contenteditable - most annoyingly tabindex is not enough

Is the recommended 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 incomplete 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?

like image 582
Tomáš Hübelbauer Avatar asked May 09 '17 18:05

Tomáš Hübelbauer


2 Answers

As a pragmatic solution use key:

  • assume that all single-character key names are printable
    • currently true except for space: " "
    • https://developer.mozilla.org/en/docs/Web/API/KeyboardEvent/key/Key_Values
  • check that no modifiers were pressed (https://stackoverflow.com/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 compatibility, consider using e.which as a fallback.

like image 151
Freddy Avatar answered Nov 11 '22 07:11

Freddy


Okay 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 coming out with a quirky remote with extra proprietary keys or something like that and all bets are off.

like image 42
Tomáš Hübelbauer Avatar answered Nov 11 '22 06:11

Tomáš Hübelbauer