Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture touchend coordinates?

I am trying to capture touch coordinate on the touchend event but get undefined. The touchstart event works good, but same concept fails on touchend. I built this code with mousedown and mouseup and that works good.

What am I missing?

div.addEvent("touchstart", function (event) {     event.preventDefault(); // to avoid scrolling     span.innerHTML = event.page.x; }); div.addEvent("touchend", function (event) {     span.innerHTML = event.page.x; }); 

FIDDLE

like image 729
Rikard Avatar asked Jul 30 '13 21:07

Rikard


2 Answers

You need to store the values on touchmove and read it in touchend.

var lastMove = null;  // Save the touchstart to always have a position div.addEvent('touchstart', function(event) {   lastMove = event; });  // Override with touchmove, which is triggered only on move div.addEvent('touchmove', function(event) {   lastMove = event; }); 
like image 145
adrenalin Avatar answered Sep 21 '22 07:09

adrenalin


I've been looking at the specification, the 4 touch events inherit from the touchEvent object, which has 3 list atributes containing information about all the touches (every finger on the screen) at the time of the event, each list saves touches based on this criteria:

changedTouches: Saves touches that have are out of the targeted element surface.

touches: Saves all current touches.

targetTouch: Saves all current touches that are within the surface of the target element.

The event touchend saves the position where the finger was lifted at changedTouches, and the nothing is saved in any of the other lists, therefore if you need to access this, you should use event.changedTouches[event.changedTouches.length-1], this returns a touch object with pageX and pageY atributes for coordinates.
The whole line would be:

span.innerHTML = event.changedTouches[event.changedTouches.length-1].pageX;


What I haven't been able to understand yet is if there's no coordinate atributes in the touchEvent object, why you get to use them at touchstart and touchmove events, and not with touchend. Maybe the implementation added this shortcut, or I missread.
like image 30
David Villamizar Avatar answered Sep 20 '22 07:09

David Villamizar