Search code examples
javascriptkeykeypressevent-listenerkeycode

Get Key Value of Key Pressed with javascriiipt


I don't find a way to print the numeric value of keypressed.

    window.addEventListener('keydown',e => {
        if(e.keyCode >=65 && e.keyCode <=90){
        console.log('Yeap letter is pressd');
    
    })

I Have a to run a condition to print only numeric value from keyPressed. But find out keyCode is been deprecated. I only find out e.code and e.key but they ddn't work as per my requirement to print the numeric value of letter. I want to check if the pressed key is letter or print the ASCII value of pressed letter


Solution

  • Use string.charCodeAt(0) to get the lower 16 bits of the first character in a primitive string value encoded using UTF-16, which is the encoding method used by JavaScript internally to represent strings in memory.

    If the UTF-16 encoded value is less than 128, the key can be represented in ASCII. However, to get ASCII control code values, use the least significant 4 bits of the ASCII letter encoding.

    window.addEventListener('keydown',e => {
        let ascii, key = e.key;
        if(key.length == 1) {
            ascii = key.charCodeAt(0);
            if(ascii < 128 && e.ctrlKey) {
                 ascii = ascii & 0x1f;
            }
        }
        if( typeof ascii == "number" && ascii < 128) {
            console.log(`ASCII code ${ascii} entered from keyboard`);
        }
        else {
            console.log( key + " is not in the ASCII character set");
        }
    });
    Type an ASCII letter.

    Running the code snippet will report on key events for the shift and Ctrl keys separately. Note ASCII encoding has largely been replaced by utf-8 encoding on the web since ASCII is not suited for transmission of non English content, or even borrowed or quoted phrases from some other language.


    Update to answer the more general question of "How to determine if a keyboard event code is for a unicode character or something else?"

    • event.key is either set to the unicode value of a key generating the event, or the "named key attrribute value" of a keys that either produce an ASCII control character such as the escape key, or don't produce unicode values such as function, arrow, navigation and system keys such as "print screen" etc.

    • Now in the W3C candidate recommendation for named key attribute values, all the key names are a string of ASCII characters with more than one character in the string.

    • The first 128 code points in Unicode are used to represent the ASCII character set.

    Combining these together implies that if the length of the event.key string is greater than one, but the first character in the string is an ASCII character, then event.key must be a key attribute value:

    window.addEventListener('keydown',e => {
        const key = e.key;
        if(key.length > 1 && key.charCodeAt(0) < 128) {
            console.log("Named attribute value: %s", key)
        }
        else {
            console.log("Unicode character '%s'", key);
        }
    });
    Click here to focus and press a key on the keyboard.

    Note that the space bar produces a space character in Unicode. When dealing with named key attribute values you could attempt to convert some of them to ASCII control codes but it is usually preferable to use their names in code:

    if( event.key === "Enter"){... handle enter key...}
    if( event.key === "Escape") {... handle escape key...}
    

    To find out what the named key attribute value of a key is you can either run a script to find out experimentally or look them up in the W3C candidate recommendation as linked above.