Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect printable keys

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?

like image 781
Andrea Avatar asked Nov 16 '10 12:11

Andrea


People also ask

How do you check if a key is pressed JS?

Detecting keys in JavaScriptdocument. onkeydown = function (e) { console. log('key down'); console. log(e); };

What is event key?

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.

Why is KeyCode deprecated?

KeyCode property was deprecated because it has been 'inconsistent across platforms and even the same implementation on different operating systems or using different localizations'.


1 Answers

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.

like image 168
Lewis Avatar answered Oct 15 '22 10:10

Lewis