20

While this code produces the expected behavior of "1" when touching the screen:

document.getElementById('someNodeId').addEventListener('touchmove', touch, true);

function touch(evt) {
  evt.preventDefault();
  alert(evt.changedTouches.length);     
  }

the same code using a jQuery selector:

 $('#someNodeId').bind('touchmove', touch);

produces the error: "TypeError: Result of expression 'evt.changedTouches'[undefined] is not an object".

(Device = iPod Touch OS 3.1.3 (7E18); jQuery 1.4.2).

How is this possible and what am I doing wrong?

Bambax
  • 2,920
  • 6
  • 34
  • 43

2 Answers2

35

Try

$(document).ready (function () {
    $("#someNodeId").bind("touchmove", function (event) {
        var e = event.originalEvent;
        console.log(e.targetTouches[0].pageX);
    });
});
Fred Bergman
  • 1,949
  • 5
  • 22
  • 30
  • 2
    an explanation of why `originalEvent` is needed will be helpful to OP and others who are not familiar with jQuery's event normalization. – Anurag Jul 06 '10 at 09:20
  • 9
    Indeed; the explanation is found here: http://stackoverflow.com/questions/671498/jquery-live-removing-iphone-touch-event-attributes "In order to 'fix' events, jQuery clones the event. In doing so, it only copies over a limited number of properties for performance reasons. However, you can still access the original event object via the event.originalEvent property." In fact I'm not sure it's very useful to use jQuery on iPhone; I went this route because of jQTouch but now I'm moving away from it. – Bambax Jul 06 '10 at 16:32
5

I use this simple function for JQuery based project

var pointerEventToXY = function(e){
  var out = {x:0, y:0};
  if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
    var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
    out.x = touch.pageX;
    out.y = touch.pageY;
  } else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
    out.x = e.pageX;
    out.y = e.pageY;
  }
  return out;
};

example:

$('a').on('mousemove touchmove', function(e){
   console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})

hope this will be usefull for you ;)

Nedudi
  • 5,639
  • 2
  • 42
  • 37