JavaScript KeyPress event and KeyCodes
» » » JavaScript KeyPress event and KeyCodes

JavaScript KeyPress event and KeyCodes

I have recently been using FabricJS for HTML5 canvas manipulation and ran into an issue of not being able to enter an apostrophe (‘) in the iText fields (an issue that has been fixed recently, but appeared in the version I am using).  After some research I found some code in the JavaScript keyPress event handler that appeared to be preventing the insertion of the apostrophe.

The core of the issue is that FireFox triggers the keyPress event on all keys, but all other browsers only trigger it for keys that produce a character value.  Thankfully, FireFox also provides us with enough detail to detect if the keyPress event has been triggered by a key with a character value or by another key.

The following tables shows the values for event.keyCode, event.which and event.charCode (it is worth noting that all three of these values are now deprecated and <a href="https://w3c.github.io/uievents/#widl-KeyboardEvent-key" target="_blank">event.key</a> should be used instead; although browser support is currently limited as the standard is a working-draft) returned from each browser.  The first value in each cell is the value for the apostrophe key, the second value is for the right arrow key (both can return a value of 39, so it makes a good example for this post).  Values with a hypen (-) mean that the event was not triggered.

KeyCodeWhichCharcode
Chrome39 / -39 / -39 / -
FireFox0 / 3939 / 039 / 0
Safari39 / -39 / -39 / -
Internet Explorer39 / -39 / -39 / -
Opera39 / -39 / -39 / -

Armed with this information the key detection is relatively simple.  In the keyPress event I get the value for event.which.  If the value is zero (0) then I return from the function.  If the value is non-zero then I continue the function and action the event.

Comments

comments