I'm finding that the delete key doesn't fire the keypress
event in Chrome, while other keys work. The problem doesn't occur in Firefox, just in Chrome, why? Here is my code:
document.addEventListener('keypress', function (e) {
console.log(e);
}, false);
You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter . keyup would be do the job better.
Once you get the key of the pressed button, then match it with the Backspace key code. A Backspace key keycode it 8. Use keydown instead of keypress . The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
Use keydown
or keyup
instead, it captures the delete key (as well as others that keypress doesn't, see http://www.quirksmode.org/js/keys.html)
document.addEventListener('keydown', function (e) {
console.log(e);
}, false);
keypress
event for (Del, End, Home,etc..) is not fired in IE, Chrome and safari.. it only works in firefox..
so you can use the keyup
or keydown
event because the keypress
event is intented for real (printable) characters. "keydown"
is handled at a lower level so it will capture all non-printing keys like DEL, End, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With