Wednesday, July 17, 2013

iOS ontouch event lag

Quite some time ago I was building a javascript app for my work that would run on an iPad.  It was a survey app that had options for the user to touch and then it would thank them for their input when they were done.  Something I noticed though was that compared to when I ran the app on my PC the iPad version seemed very sluggish.  The buttons used onclick events which one would use on any average page but I knew there was a special iOS only event called ontouch so I thought that if I changed all my events to those instead it might fix the issue.

I was wrong.

To illustrate this for you I have put together a simple little "game" that has arrow buttons and a little "character" that those buttons move around the screen.  I use the terms VERY loosely.  At any rate, if you run the following code on your iPad/iPhone/iPod Touch you will be able to see what I'm talking about.

To play around with this you will need to put this html file on a web server.  If you don't have access to a real one you can set up a local one on you wifi network using WAMP.

Once you get it up and running it should look something like this -

As you can see.  It takes a bit from the time you touch the buttons until the time it actually moves the hero.  I did a lot of digging (so you don't have to) and found out that there is ANOTHER iOS specific event called ontouchstart.

Replace all the ontouch events with ontouchstart and fire up the "game" again.  See the difference?  Instant gratification.

At first I had thought that perhaps iOS devices were just really bad at handling javascript but it turns out the little bit of lag is there on purpose.  As they say "its a feature not a bug".  The reason for two different events is that if somebody accidentally touches something they didn't want to, like a submit button, the user can still change their mind by swiping their finger to change the behavior from a touch event to a scroll one.  With ontouchstart though, there is no turning back!

So, in the event you were wondering why your javascript buttons were functioning like crap on an iOS device, now you know.          ...and knowing is half the battle!