Ben McCallum's Blog

Dissecting ASP.NET MVC3, CSS3, HTML5, jQuery and a whole lot of other things ending with numbers…

jQuery live() function and Safari mobile version bug

Recently I came across an interesting problem. As you can now see on my website @ http://reach4urPhone.com/player/weapons?gamertag=xBLACK%20V3N0Mx I have a table displaying a player’s weapon stats in a table. By pressing the arrows above the columns the user can roll through varying columns to show more stats, an effective way of cramming more stats into a mobile interface.

To do this I simply wrote a click handler with the appropriate functionality and bound it to the element via jQuery’s live() function.


$('#rightArrow').live('click', function () {
//...
});

It was necessary to use the .live() jQuery method to bind my click handler to elements inserted into the DOM after the initial page load (ie. via AJAX). Everything seemed to be working fine on my desktop development machine in Chrome, Safari, Firefox and IE9. But when I deployed the site and viewed it on my iPhone and iPad the click handler was never called. After some digging I found this jQuery bug report: http://bugs.jquery.com/ticket/5677

It seems that the live jQuery method is never executed in the Safari mobile environment, or at least does nothing. So until the jQuery team handles this situation I’ve implemented the following workaround…
Instead of binding a function to the event, use the old-fashioned way by adding this to your clickable elements:
onclick="functionName(this)"

and refactoring your existing code into functions with the appropriate names of course and the structure function functionName(obj) { ... }

Note: Passing this to the function enables you to identify the element which was pressed so you can perhaps give a clicked appearance through CSS by doing
$(obj).css('...', '...')

Finally, I realise this is not the “Unobtrusive JavaScript” way but hopefully the jQuery team will implement a solution soon. Full solution is available on my site as of this post.

Advertisements

Single Post Navigation

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

%d bloggers like this: