Keycode 229

I ran into a pretty obscure mobile JS error, and thought I should share it, on the off-chance someone else finds it as well.

I had built a click event attached to key codes corresponding to letters and numbers – so, when the user hit a letter, punctuation, or number, my event would fire.

if((e.which = 48  e.which = 90) || etc...){

This worked wonderfully until I tested on Android. My event wasn’t firing. It was working in DevTools mobile view, but not on my phone. Worse yet, there’s no easy way to see a console on mobile, so I resorted to appending console.log messages right onto my live site (since I couldn’t run localhost:3000 on mobile). Not pretty.

Anyway, I got to the root of the issue. Every key on mobile was registering as

e.which == 229

This wasn’t happening on mobile view on DevTools because the key codes were being read correctly. Turns out this is a well known issue. My solution was simple – to fire the event on e.which == 229. However, this didn’t actually give me the key code.

It seems like there’s no ideal solution. Some people suggest using a keypress and textInput listeners, which works intermittently. There is also this workaround, which involves getting the last character typed in a field and determining its char code (a number representing a Unicode character, found through the keypress listener), not key code (a number representing the key on the keyboard the user pressed, found through the keydown/keyup listener). Here’s a neat tool to differentiate.

Here’s the jQuery solution, though I think you can accomplish the same thing by using a keypress listener.

var text = $("#some-textarea").val();
var keyCode = text.charCodeAt(text[text.length - 1]);

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s