Skip to content Skip to sidebar Skip to footer

E.key Is Not Supported In Most Browser

In a event listener I am using e.key, but it seems it is not supported by many older browsers. From https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode and https

Solution 1:

You use whichever is supported by checking them all, starting with the preferred e.key which will be supported by all browsers in time

if (e.key) {
     var key = e.key;
} else {
    var code = e.which || e.keyCode;
    var key  = String.fromCharCode(code);
}

They should return the same character

document.getElementById('test').addEventListener('keypress', function(e) {
    var code = e.which || e.keyCode;
    var key  = String.fromCharCode(code);
    
    console.log(key, e.key)
});
<p>Type in the input !</p><inputid="test">

Note that keyup and keydown events will return different keycodes for certain keys.

Solution 2:

I tried implementing e.key in my application because I read on MDN that e.keyCode and e.which are both deprecaenter code hereted as well. However, all I see anywhere is still implementations of e.keyCode || e.which, and that exact code still works everywhere and well for me. MDN does not provide any solution or viable implementation for e.key and I see no key codes anywhere either. I say the documentation is wrong. And as stated here, e.key is NOT the same as e.keyCode or e.which. I would like to know what actually is supposed to be replacing e.keyCode or e.which. I am using it for example, in a keydown event. e.key breaks my code. This is the code:

[...inputs].forEach(input => input.addEventListener('keydown', (e) => {
    console.log(Array.isArray([...inputs]))
    console.log([...inputs])
    const chord = e.keyCode || e.whichif (chord === 8) {
        e.preventDefault()
        e.currentTarget.value = ''
        heading1.innerHTML = `User Registration Form`;
        heading1.style.color = `#228b22`;
    }
}))

And this is the link to the live application:

User Registration Form Using JS Constraint Validation API

Post a Comment for "E.key Is Not Supported In Most Browser"