Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery's event.which gives different results in Firefox and Chrome?

Have a look at this live demo (from jQuery's site).

Clicking - (dash) in Firefox says that event.which is 173, while doing the same in Chrome produces 189.

This jQuery page says that event.which should be normalized for cross browser consistency. But, it looks like this is not true.

Why is this inconsistency?

like image 225
Misha Moroshko Avatar asked Aug 11 '13 23:08

Misha Moroshko


1 Answers

This jQuery page says that event.which should be normalized for cross browser consistency. But, it looks like this is not true.

jQuery normalizes the property name (e.g., always which, rather than which or keyCode depending on browser), but not the value of the property, which would be dramatically more complex.

The value for the key you get from keydown / keyup will vary not only by browser, but by keyboard layout. There are lots of gory details on the JavaScript Madness: Keyboard Events page by Jan Wolter. Amongst other things, you can see on that page that for that key, Firefox will give you 109, IE (and apparently Chrome) will give you 189, and Opera apparently used to go with 45 (but in my tests on Linux, they now go with 109).

For printable keystrokes (like -), you're better off with the keypress event, which gives you the resulting character.

like image 179
T.J. Crowder Avatar answered Nov 03 '22 04:11

T.J. Crowder