Thursday, April 8, 2010

Click events on iPad


Designing a web page to be run on an iPhone, either as an embedded UIWebView or under Safari, you may want to consider how you handle click events. Click events feel sluggish because they don't trigger right away due to a delay to make sure the click isn't a double click. If your site requires snappy interaction (e.g. a game) then you have two options:
  1. Use 'touchstart' instead of 'click' when binding events
  2. If your app requires that you bind to 'touchend' then you'll need to remove the delay (good article)
iPhone developers are likely debugging their pages using Safari, so they need a way to be able to have code work in a click (Safari) and a touch (iPhone/iPad) environment. Here's an example of how to achieve this using jQuery.

First define a way to test if you're on an iPad:

(function($) {
    var userAgent = navigator.userAgent.toLowerCase();
    $.browser = {
        version : (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [ 0'0' ])[1],
        ipad : /ipad/.test(userAgent),
        safari : /webkit/.test(userAgent),
        opera : /opera/.test(userAgent),
        msie : /msie/.test(userAgent) && !/opera/.test(userAgent),
        mozilla : /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
    };
})(jQuery);

Then set a global variable with the type of event you want to look for e.g.

window.clickEvent = 'click';
if($.browser.ipad) {
    window.clickEvent = 'touchstart';
}

Bind events based on window.clickEvent e.g.

    $('.someEl').bind(window.clickEvent, function(event) {
        handleSomeElEvent();
    });

Now you can debug your app in Safari and run your app on the iPad without code changes.