views:

279

answers:

4

I started using touch events for a while now, but I just stumbled upon quite a problem. Until now, I checked if touch capabilities are supported, and applied selective events based on that. Like this:

if(document.ontouchmove === undefined){
    //apply mouse events
}else{
    //apply touch events
}

However, my scripts stopped working in Chrome5 (which is currently beta) on my computer. I researched it a bit, and as I expected, in Chrome5 (as opposed to older Chrome, Firefox, IE, etc.) document.ontouchmove is no longer undefined but null.

At first I wanted to submit a bug report, but then I realized: There are devices that have both mouse and touch capabilities, so that might be natural, maybe Chrome now defines it because my OS might support both types of events.

So the solutions seems easy: Apply BOTH event types. Right?

Well the problem now take place on mobile. In order to be backward compatible and support scripts that only use mouse events, mobile browsers might try to fire them as well (on touch). So then with both mouse and touch events set, a certain handler might be called twice every time.

What is the way to approach this? Is there a better way to check and apply selective events, or must I ignore the problems that might occur if browsers fire both touch and mouse events at times?

A: 

Try creating a dummy element and attaching a touch event handler to it, then check if the handler is of type "function". This is not foolproof though as some browsers will allow touch event handlers although they are running on a non-touch device - but it's probably as close as you'll get. So, something like this:

var hasTouch = function() {
    var dummy = document.createElement("div");
    dummy.setAttribute("ontouchmove", "return;");
    return typeof dummy.ontouchmove == "function" ? true : false;
}

Happy coding!

Ola Tuvesson
put a () after the hasTouch, so it will be a boolean and will only be executed once :)
M28
+1  A: 
Long Ouyang
+1  A: 

Is this too obvious?

if(document.ontouchmove !== undefined || document.ontouchmove == null){
    //apply touch events
}else{
    //apply mouse events
}
Phil
scunliffe