Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't fire keypress event when press delete key

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);
like image 814
qiu8310 Avatar asked Apr 17 '12 08:04

qiu8310


People also ask

How do I capture a delete key press?

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.

Does backspace count as keypress?

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.

What is the difference between Keydown and keypress events?

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.


2 Answers

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);
like image 77
Josh Davenport-Smith Avatar answered Sep 30 '22 18:09

Josh Davenport-Smith


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

like image 31
BrainCoder Avatar answered Sep 30 '22 18:09

BrainCoder