javascriptkeyevent

How to check KeyboardEvent.key in specific range in Javascript


In Javascript, I have callback function for keydown event. I use keyCode and which properties to detect which keys user pressed.

var keyPressed = event.keyCode || event.which;
if (keyPressed > 47 && keyPressed < 58) {
    //do something
}

It works well. However, this properties are deprecated, I switch to key property. When I replace code, it does not work correctly.

if (event.key > 47 && event.key < 58) {
        //do something
}

I can't check user's pressed key in range.


Solution

  • For printable characters, .key() returns a non-empty Unicode character string containing the printable representation of the key.

    Essentially: for ASCII characters, you get the character itself rather than its ASCII code.

    So, for digits you could just do:

    var myInput = document.getElementsByTagName('input')[0];
    
    myInput.addEventListener("keydown", function(event) {
      if(event.key >= "0" && event.key <= "9") {
        console.log('digit: ' + event.key);
      }
    });
    <input>

    For letters, you'll also have to check that .key() returns a single character because a non-printable key such as delete will be encoded as "Delete", which would pass the test "Delete" >= "A" && "Delete" <= "Z".

    var myInput = document.getElementsByTagName('input')[0];
    
    myInput.addEventListener("keydown", function(event) {
      if(event.key.length == 1 && event.key >= "A" && event.key <= "Z") {
        console.log('capital letter: ' + event.key);
      }
    });
    <input>