Category : Javascript | Author : Chtiwi Malek | First posted : 3/3/2013 | Updated : 9/26/2017
Tags : touch, drag, javascript, mouse, website, ux, ui
Add touch screen support to your website (The easy way)

Add touch screen support to your website (The easy way)

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 :
function touch2Mouse(e)
  var theTouch = e.changedTouches[0];
  var mouseEv;

    case "touchstart": mouseEv="mousedown"; break;  
    case "touchend":   mouseEv="mouseup"; break;
    case "touchmove":  mouseEv="mousemove"; break;
    default: return;

  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.
About the author :
Malek Chtiwi is the man behind
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.
Comments & Opinions :
works very good, thanks.
- by Joe on 3/5/2013
Thanks for this, I was strugling a lot trying to make it work, and this helped me a lot!
- by Alessandro on 8/4/2020
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :