jQuery and Mobile Safari touch events

In previous posts I mentioned how to use touch events on the iPad with Mootools. I was wondering how I could do the same with JQuery.Due to the way JQuery is designed you can't extend prototype in the same way you can with Mootools. Instead we use bind events to do the swap. In this example I am looking at mousemove and touchmove and how to get the mouse or finger position. Firstly we need a function that will work out if we can use touch events on our page.

function doesTouch()
{
try
{
// if we can make touch events return true
document.createEvent("TouchEvent");
return true;
}
catch(e)
{
return false;
}
}


The page tries to create a touch event and if it can it returns true, else false.We then need a custom event handler to tell the browser whether it should use a mousemove or touchmove event.

jQuery.fn.touchMouseMove = function(e) { return this.bind(doesTouch() ? 'touchmove' : 'mousemove',e); };
When ever this is called it checks whether the TouchEvent can be created or not. Then fires the appropriate event off. We then call that event like we would with .click() etc

jQuery('#overlay').touchMouseMove(function(e){
e.preventDefault();
});


In this case I have a div element with the id of content. Now if we want to access the TouchEvent properties we need to check again what event was fired.

if(e.type == 'touchmove')
{
console.log(event.touches[0].pageX)
}
if(e.type == 'mousemove')
{
console.log(e.pageX)
}


We check if the event type is a mosuemove or touchmove. I have found that to access the touch event properties you have to call it by using event.toucheventproperty. I am not sure why it only responds from event. I can't find any documentation on why this is the case but that just seems to the case. Its interesting because if you have function(e) { e.preventDefault() } the default touch options are disabled. Anyway to get the pageX with touch we use event.touches[0].pageX. the touches[0] is a single finger touch, if you want to access a second finger you would use touches[1]. With mousemove we can simply use our e.pageX.

Altogether

jQuery(document).ready(function(){
function doesTouch()
{
try
{
// if we can make touch events return true
document.createEvent("TouchEvent");
return true;
}
catch(e)
{
return false;
}
}
jQuery.fn.touchMouseMove = function(e)
{
return this.bind(doesTouch() ? 'touchmove' : 'mousemove',e);
};
jQuery('#overlay').touchMouseMove(function(e){
e.preventDefault();
if(e.type == 'touchmove')
{
console.log(event.touches[0].pageX)
}
if(e.type == 'mousemove')
{
console.log(e.pageX)
}
});
});


I hope this helps anyone looking to access the TouchEvent properties with JQuery. By the way this method can be used to bind touchstart to mousedown events or any other event for that matter. Also very its very useful for dealing with objects that have mouseover effects that you want to turn into clicks for devices with touch only input methods.