Detecting support for touch events
Q: How can I determine whether the current browser supports touch events?
A: Don't look at the user agent string for a certain browser name or version. Instead, use JavaScript to test for the existence of the createTouch property on the document object.
if ("createTouch" in document) { // touch events are supported }
I often like to test for touch events support, then set event handlers accordingly. This lets me develop new code on the Desktop, and still get the immediate feedback and responsiveness that touch events provide on iOS devices.
For example:
function init() { var down = "mousedown"; var up = "mouseup"; if ('createTouch' in document) { down = "touchstart"; up = "touchend"; } var myElement = document.querySelector("#myElement"); myElement.addEventListener(down,doSomething,false); myElement.addEventListener(up,doSomething,false); }
This easy test for touch events is also handy for simply getting the wording in your UI correct. For instance, the full example says "Tap" instead of "Click" if touch events are supported.
Be sure to try out the full example in your Desktop browser, and in Safari on iOS.
More info:
The W3C spec for Touch Events
Handling Multi-touch events and gestures, in the Safari Web Content Guide
An oldie but goodie from WWDC 2010: Session 508: Adding Touch and Gesture Detection to Web Pages
Disclaimer: I don't own any Android devices, so I've only tested this on iOS on iPhone and iPad!
Tweet
// <![CDATA[ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs'); // ]]>














