In this article we will add touch support to an existing web application simply by mapping touch events to existing mouse events handlers. If you are already handling mouse events just copy and paste this code.
First we need to listen to touch events and call a function 'touch2Mouse'
each time a touch event is fired:
document.addEventListener("touchstart", touch2Mouse, true);
document.addEventListener("touchmove", touch2Mouse, true);
document.addEventListener("touchend", touch2Mouse, true);
The following function will initiate and fire mouse events (event.initMouseEvent
), for each touch events type we'll fire the equivalent mouse event :
Touchstart => Mousedown
Touchend => Mouseup
Touchmove => Mousemove
and then we will cancel the original touch event using preventdefault
var theTouch = e.changedTouches;
case "touchstart": mouseEv="mousedown"; break;
case "touchend": mouseEv="mouseup"; break;
case "touchmove": mouseEv="mousemove"; break;
var mouseEvent = document.createEvent("MouseEvent");
mouseEvent.initMouseEvent(mouseEv, true, true, window, 1, theTouch.screenX, theTouch.screenY, theTouch.clientX, theTouch.clientY, false, false, false, false, 0, null);
Just follow the same logic to wire other events (mouseover, click, dblclick, ...)
This should work on all browsers and devices, personally I tested it successfully on IE, Firefox, Google Chrome, Opera, Firefox for android, Chrome for android, Opera for android and iPhone.
A full working example can be tested here
Hope you like this and don't hesitate to comment, Thanks.
Chtiwi Malek on Google+
About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.