You might have faced this issue before or even might have wondered – How to write a single piece of code that establishes correct event in the device i.e touch events for mobile web browsers and mouse events for desktop browsers. You need not hard code the events for your app code. Once you detect and handle those events, you can run your app everywhere – mobiles and computer browsers. Normally when we develop an app for mobile browsers we test it in a desktop browser, so if you have touch events hard-coded into your script then it is a pain to change the script and make it work for computer browsers(replacing touch events with mouse events) and then change it back again to touch for mobiles. So, here is a small script/trick to universally handle the event and need not worry about devices,
var isTouchSupported = 'ontouchstart' in window; var startEvent = isTouchSupported ? 'touchstart' : 'mousedown'; var moveEvent = isTouchSupported ? 'touchmove' : 'mousemove'; var endEvent = isTouchSupported ? 'touchend' : 'mouseup';
If you see the first line of the script, it detects if ontouchstart property is available in the global window object. It it is available or it is a part of the window object, then it returns true else it returns false. Note that ontouchstart is a standard javascript touch event attribute. Now, if you are making this check in a computer browser (for e.g FF, Chrome or IE) then ontouchstart is not a property of the window object. So isTouchSupported will be set to false. Had it been a mobile browser (e.g iOS, Android) then ontouchstart would have been automatically a part of the window object and correspondingly isTouchSupported variable will set to true. This is all we need to detect. The next three lines establish a common platform for the touch vs mouse events i.e I am mapping the touch events to its corresponding mouse events.
Now, all you need is to register the event listener to your element so that some action is performed when the event is triggered on the element. Here is an example, (where myButton is the ID of my imaginary button)
document.getElementById("myButton").addEventListener(startEvent,function(){},false);
The startEvent variable acts as a placeholder. It will be replaced by mousedown for computer browsers and touchstart for mobile browsers. Similarly the other two events can be used. This way a single app can run everywhere.
Here is a good example with the usage (make sure you look at the javascript script code) - http://jbkflex.wordpress.com/2012/07/21/replicating-the-iphone-swipe-gesture-common-code-for-mobiles-and-desktop-browsers/
Here is another one - http://jbkflex.wordpress.com/2012/07/25/360-degree-car-rotation-common-code-for-mobiles-and-computer-browsers/
Please do suggest me if there are any better methods of mapping touch v/s mouse events.