Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting browser capabilities and selective events for mouse and touch

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?

like image 702
treznik Avatar asked Oct 15 '22 06:10

treznik


1 Answers

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!

like image 93
Ola Tuvesson Avatar answered Oct 18 '22 13:10

Ola Tuvesson