E.key Is Not Supported In Most Browser
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>
<input id="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 here
ted 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.which
if (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:
Post a Comment for "E.key Is Not Supported In Most Browser"