I'm trying to get a cross-browser way to listen to keyCode
of user's keyDown
.
For mobile browsers, I have to trigger the virtual keyboard, so I use an input hidden by css, triggered with a click
event. This works well except that when I try to listen to keycode, on fennec (mobile Firefox), I've got strange behavior.
Here is the function I use to listen to keycode
.
document.querySelectorAll('input')[0].addEventListener('keydown', handler);
function handler(e) {
e.preventDefault();
var k = (e.which) ? e.which : e.keyCode;
document.getElementById('log').innerHTML = k;
this.style.backgroundColor = "#FFAAFF";
}
<input type="text" />
<span id="log"></span>
In Firefox for android (v34 to v37), it won't fire until the user typed return⏎.
Actually, I found that if the value of the input is not empty, it works well, at least on load. So I thought of a workaround like this one :if(this.value=='')this.value='*';
Seems to work but if you spam it, the backspace ⌫ isn't blocked, so when the input is cleared, the bug comes back : the workaround doesn't fire either.
+This a ugly workaround, which I'm sure will create other bugs in other browsers.
document.querySelectorAll('input')[0].addEventListener('keydown', handler); function handler(e) { if(this.value=='')this.value='*'; e.preventDefault(); var k = (e.which) ? e.which : e.keyCode; document.getElementById('log').innerHTML = k; this.style.backgroundColor = "#FFAAFF"; }
<input type="text" value="*"/> <span id="log"></span>
In B2G (Firefox Os 1.3 on device or 2.0 emulated) the behavior is even odder:
the function only readskeyCode
for backspace⌫(keycode8
) or return⏎(keyCode13
) keys. Any other key will return0
.
So, my question is, do you know a better cross browser way to listen to keyCode
, a one working in all major browsers, desktop or mobile, and on fennec?
Ps: even if I write my app in vanilla-js, it's ok for me to see solutions with any library.
keyup
/keydown
events don't fire until the user enters the input (when thechange
event fires). – Vasta