Monday, March 18, 2013

keypress event name is misleading

The keypress event is not triggered when user do backspace or delete on keyboard. This is true according to [webkit-dev] Changes to keyboard event handling

If you want to detect backspace or delete key depress, use keyup or keydown event. keypress event name is misleading, it is actually meaning character inserted (textenter?) 

keydown: Fires when the user depresses a key. It repeats while the user keeps the key depressed.
keypress: Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
keyup: Fires when the user releases a key, after the default action of that key has been performed.

According to above definition, when the user presses special keys such as the arrow keys, backspace, or delete key, the browser should NOT fire keypress events. For cross browser behaviors, check out
http://www.quirksmode.org/dom/events/keys.html

Here is my backspace and delete key depress detection code:
if (e.keyCode === 46 || e.keyCode === 8)  {
     //do something
     return false;
}

1 comment:

  1. When input some languages like Japanese, we need use keydown, otherwise the event will fall through to textarea/input. Simply put, use keydown in most cases.

    ReplyDelete