I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.
Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?
Detecting keys in JavaScriptdocument. onkeydown = function (e) { console. log('key down'); console. log(e); };
KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ( keydown , keypress , or keyup ) identifies what kind of keyboard activity occurred.
KeyCode property was deprecated because it has been 'inconsistent across platforms and even the same implementation on different operating systems or using different localizations'.
Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key
to detect a printable key via its length.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">
Besides that, you can also detect any other keys from the list, like Enter
, Delete
, Backspace
, Tab
, etc.
This method is much more reliable simply because unlike event.which
, event.key
is already standardized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With