51

If I catch all touchend events from mobile devices with:

$(document.body).bind('touchend', function (e) {
var touch = e.touches[0]; // doesnt work
...

I need to get the touch.screenX, touch.screenY, touch.clientX and touch.clientX from the e paramter. All the examples I've seen suggest that e.touches will be a collection, and you can get at the touch details with e.touches[0]. In my tests on an ipad, e.touches is always undefined. I'm not using any jquery plugins.

Also tried e.targetTouches, which is also undefined.

Can anyone help?

Thaddeus Albers
  • 4,094
  • 5
  • 32
  • 42
Matt Roberts
  • 26,371
  • 31
  • 103
  • 180

2 Answers2

104

Actually, released touches will be found in the changedTouches array, ie:

e.changedTouches[0].pageX // get the end x page coordinate for a released touch

I think this is slightly more reliable than going through the originalEvent property.

You can read more on changedTouches here: http://www.w3.org/TR/touch-events/#changedtouches-of-a-touchevent

Gopherkhan
  • 4,317
  • 4
  • 32
  • 54
  • I agree, this is the correct solution. I, myself, am using this since it has the correct data needded and why mix up more APIs than needed. – Chef Pharaoh Dec 07 '12 at 22:42
  • 2
    This is not the case with android if you are using jQuery. $('#test').on('touchend', function (evt) { console.log(evt.changedTouches); }); is empty, same if you do $('#test').bind('touchend'... but if you cut jquery out of the equation and do getElementBy and addEventListener it works.. – WORMSS Aug 29 '14 at 00:12
  • @WORMSS: The answer is unclear with regard to the jQuery event.originalEvent property. That issue is addressed specifically here - http://stackoverflow.com/questions/14999724/touchstart-in-javascript-no-longer-returns-touchlist – Nolo Sep 23 '14 at 16:17
  • e.originalEvent.changedTouches[0].pageX is the correct answer! [EDITED 20-11-2017] – devpelux Nov 20 '17 at 17:41
  • 1
    This ended my weeks of struggle. Thank you – thednp Jan 03 '20 at 20:13
10

The touches property is an TouchList object. You can see the TouchList class reference here.

If you monitor its length property with this example code on #log div:

$('#element').bind('touchstart', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

$('#element').bind('touchmove', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

$('#element').bind('touchend', function(event) 
{
    $('#log').append(event.originalEvent.touches.length+'<br/>');
});

you will obtain 1 while executing touchstart and touchmove, an 0 when executing touchend. That is why you obtain undefined from e.touches[0].

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
javibilbo
  • 101
  • 1
  • 3