code


5
Jun 10

Using Mobile Safari Touch Events

As Thomas Fuchs documented here, touch events on Mobile Safari (and maybe Android, although I haven’t tested) trigger much faster than mouse click events, and can make your web application appear much more responsive with only a few small code changes. The snippet below will allow you to bind and trigger mouse clicks as usual using jQuery, but will use touch “clicks” instead in browsers that support it.

I’ve experimented with this myself, and it makes a huge difference! And here I was just thinking that my iPhone was slow…

	// "'createTouch' in document" will return true in Apple's Mobile Safari. Otherwise detect Android directly.
	function supportsTouch() {
		var android = navigator.userAgent.indexOf('Android') != -1;
		return android || !!('createTouch' in document)
	}

	// Use $('a').touchOrClick instead of $('a').click in your code.
	jQuery.fn.touchOrClick = function(efunc) {
		if (typeof efunc == 'undefined') {
			return this.trigger(supportsTouch() ? 'touchstart' : 'click');
		} else {
			return this.bind(supportsTouch() ? 'touchstart' : 'click', efunc);
		}
	};

Hope you enjoy.