Touch based event mapping

From a response on StackOverflow

I’ve captured the touch events and then manually fired my own mouse events to match.

Touch to mouse is wrong.
Mouse to touch is good.

Because mouse it’s more simple than touch. How would you simulate multi-touch into mouse events? Sure there is a way but it’s awful and not lightweight. That’s why you should build for touch. Starting from now on.

Sure, there is no problem using touch to mouse plugins on active websites, but using them on new projects it is rather regressive and old.

Reasons why you should use this technique

  • Simulates events only in desktop browsers
  • Native touch events ( because mobile devices have less processing power )
  • You’re creating future-proof code

So the point here is that we shouldn’t make mobile devices behave as a we know( like a mouse ), but make the mouse behave as a finger.

Of course there are inconsistencies like mouseover, mouseout and rightclick which belong to desktop browsers ant can’t be simulated into touch events. And this frustrating bug.

jQuery plugin

I don’t think I’m the only one upset that jQuery doesn’t support touch events yet. Every code can be improved, so please contribute to this project on GitHub to keep it going.

The idea is to detect if the device supports touch events and from there on, to simulate or to use the default apis. Thanks to Modernizr for the touch events detection code.

See the example

( function( $ ){

	$( document ).ready(function(){

		var position = { top: 0, left: 0 }, doc = $( document ), elm = $( '#box' ), startpos = {};

		elm.on( 'touchstart',function( e ){

			// android bug, it will prevent links and buttons from working

			var touch = e.changedTouches[ 0 ];

			position = elm.position();
			startpos.x = position.left - touch.pageX;
			startpos.y = - touch.pageY;

			// add drag functionality
			doc.on( 'touchmove', function( e ){

				var touch = e.changedTouches[ 0 ];
					top: startpos.y + touch.pageY, 
					left: startpos.x + touch.pageX 

			}).on( 'touchend', function( e ){ 'touchmove touchend' );


		}).click( function(e){

			// don't follow the link in desktop browsers


		// multiple bindings
		elm.on( 'touchstart',function(){

			elm.css({background:'green' });

		}).on( 'touchend', function(){

			elm.css({background: 'red'});



})( jQuery );

Source code is very small, 3 kb unminified and 1.3 minified.