Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery preserve touch events properties?

Tags:

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?

like image 889
Bambax Avatar asked Jul 06 '10 06:07

Bambax


2 Answers

Try

$(document).ready (function () {
    $("#someNodeId").bind("touchmove", function (event) {
        var e = event.originalEvent;
        console.log(e.targetTouches[0].pageX);
    });
});
like image 153
Fred Bergman Avatar answered Sep 28 '22 09:09

Fred Bergman


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 ;)

like image 43
Nedudi Avatar answered Sep 28 '22 08:09

Nedudi