Skip to content

Instantly share code, notes, and snippets.

@jalex19100
Created March 19, 2019 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalex19100/f37a2c922150031ed5308caa0f0893b2 to your computer and use it in GitHub Desktop.
Save jalex19100/f37a2c922150031ed5308caa0f0893b2 to your computer and use it in GitHub Desktop.
Treat touch events as mouse events. Useful for legacy code that you cannot change but could load a small piece to support touch events.
/* 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;
switch(e.type)
{
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);
theTouch.target.dispatchEvent(mouseEvent);
e.preventDefault();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment