I'm using the below code to bind "click" or "touchstart" events (using jQuery's on(eventType, function() { ... })
).
var what = (navigator.userAgent.match(/iPad/i)) ? 'touchstart' : 'click';
Later on:
$foo.on(what, function() { ... });
... which works great for iPad and "everything else", but I'm concerned that the above code has "iPad tunnel vision"...
My question(s):
Do all other devices (for example, Android tablets) have similarly named "touchstart" events? If so, how can I improve the above code so that I can account for those event types?
In other words, how can I account for a wider range of touch devices in above code (not just iPad)?
EDIT #1
What do you folks think about this:
var foo = ('ontouchstart' in window) ? 'touchstart' : ((window.DocumentTouch && document instanceof DocumentTouch) ? 'tap' : 'click');
Note: Most of the above logic is from Modernizr here.
The above appears to work for Firefox/iPad... I don't have much else to test on at this time.
What I like about the above is that I'm not UA sniffing. :)
Is tap
a good default for all other touch devices?
EDIT #2
Some interesting information here, which links to this:
Creating Fast Buttons for Mobile Web Applications
Not a direct answer really, but gives a lot of details of the situation devs face when facing click-related events for multiple platforms and devices.
EDIT #3
Some good info here too:
Android and iPhone touch events
Android and iPhone versions of WebKit have some touch events in common:
touchstart - triggered when a touch is initiated. Mouse equivalent - mouseDown touchmove - triggered when a touch moves. Mouse equivalent - mouseMove touchend - triggered when a touch ends. Mouse equivalent - mouseUp. This one is a bit special on the iPhone - see below touchcancel - bit of a mystery
After reading that, I think I'll change the code above to this:
var foo = (('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch)) ? 'touchstart' : 'click';
When I first asked my question - not having access to anything other than an iPad/iPhone - I assumed touchstart
was an iOS-specific event; it now looks like touchstart
and click
will cover most, if not all, of the bases for touch devices.
August 2014 update:
If it's of any help, I've posted some utility classes here:
-
[no-js] [no-touch] JavaScript utilities to put in of HTML templates that will add
js
ortouch
classes for use in CSS and/or JS.