Tuesday, May 4, 2010

iPhone Touch Events

Dear Apple,

This is one area that is fairly poorly documented.

In javascript with mobile safari I want to capture the mousemove event on a canvas object. It works fine in normal browsers and I'm using the technique on top here to do it in Firefox, but mobile safari won't let you use mousemove in the same way.

Mobile safari actually provides and even better event for you to use. It's called touchmove. Touch move already knows if your finger is on the screen so you don't have to check for that in your callback function. The code below replaces the code above when developing for mobile safari, however leaving them all in works well and provides mobile safari + desktop browser support for the application



The old way:
$("#canvas").mousedown(function(e) {
 e.preventDefault();
 click = true;
});
   
$("#canvas").mousemove(function(e) {
 e.preventDefault();
 if (click) { 
  sharky.y =  e.clientY;
 }
}); 

$("#canvas").mouseup(function(e) {
 e.preventDefault();
 click = false;
 sharky.y =  e.layerY;
 return false;
});



The new way:
$("#canvas").bind("touchmove", {}, function(e) {
  e.preventDefault();
  touch = window.event.targetTouches[ 0 ];
  sharky.y =  touch.clientY;
});
   


Thanks to:
Touching and Gesturing on the iPhone
Apple Developer Reference
Drawing On The iPhone Canvas With jQuery And ColdFusion

No comments:

Post a Comment