views:

642

answers:

2

In an attempt to follow best practices, we're trying to use the proper JavaScript/jQuery events according to what device you are using. For example, we're building a mobile site that has an tag that will have an onclick or touch event. In the case of an iPhone, we'd like to use the "touchstart" event. We'd like to test if their device supports "touchstart" before we bind that handler to the object. If it doesn't, then we will bind "onclick" instead.

What is the best way to do this?

+3  A: 

You can detect if the event is supported by:

if ('ontouchstart' in document.documentElement) {
  //...
}

Give a look to this article:

The isEventSupported function published there, is really good detecting a wide variety of events, and it's cross-browser.

CMS
I'm sort of tempted to +1 this, but I know that Firefox will return `false` here for the wrong reasons. Firefox returns false for all events checked in this manner (I know, it's one of those rare situations where Fx sucks). The article does go into that though, so you get your +1 ;-)
Andy E
great resource. Thanks for the quick help!
Alex
+1  A: 

You could check if typeof document.body.ontouchstart == "undefined" to fall back to normal dom events

antimatter15