When handling key[Up|Down|Press] events, should I use .which or .keyCode? Can I have some example code for handling the three keyboard events in jQuery? Can you do it without jQuery? I want it to work reliably in every browser.
Update
Strangely, jQuery's event.which normalization wasn't working for my handleKeyPress(event) handler:
// Add which for key events
if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
event.which = event.charCode || event.keyCode;
}
I'm getting this before and after this normalization inside handleKeyPress (it's not setting event.which to the value in event.keyCode):
- event.which = 0
- event.charCode = 0
- event.keyCode = 40
However, the code works if I use handleKeyDown instead. I think it has to do with keypress vs. keydown; the code works for my handleKeyDown(event) handler.
Unfortunately, I need to use keypress (not keydown), since I want to use the arrow-keys for navigation: if the user presses and holds an arrow key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character).