Friday, February 28, 2014

JavaScript Simulate Touch Events on Phone to Mouse Events

Have you ever faced an issue that some of the JavaScript code for handling touch events  does not work on phone?

For example take an example of jQuery draggable. when you test it it does not work in mobile browser. The reason is, it binds and tracks mouse events while phone we don't have mouse events but we have touch events and that's why jQuery draggable will not work. Same way if you have some other old JavaScript framework which may not work on phone because of this issue. What if you have to use that framework or code and you can not change it because it's minified files? Here in this blog we will explain the solution for it. Basically we will simulate touch events to mouse events so this types of code works.

We will convert

touchstart => mousedown
touchmove => mousemove
touchend => mouseup

Check the following code.

function touchToMouseHandler(event) {
var touch = event.changedTouches[0];

var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);

touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}

function initHandlers() {
document.addEventListener("touchstart", touchToMouseHandler, true);
document.addEventListener("touchmove", touchToMouseHandler, true);
document.addEventListener("touchend", touchToMouseHandler, true);
document.addEventListener("touchcancel", touchToMouseHandler, true);
}


So here initHandlers function will add listers to touch events and function touchToMouseHandler will convert touch events to mouse events and simulate the action. Above code you can out in JS file on script tag in your html file and call the initHandlers function. With this above code you can use code with mouse events on phone browsers. Hope this helps you.

No comments:

Post a Comment