I\'m playing with touchstart and touchend events on my iPhone. I built a sample page that has div that if you touch it and scroll the page, it should return the y coordinate
Ok the quick answer is you can't detect a touch when the finger leaves the screen (touchend
).
My first example proves that: http://jsfiddle.net/Y4fHD/
Now to the workaround. Or call it what you want. Maybe it makes sense not detection on the touchend
event because the the touch has ended.
Bind the handler on the touchmove
event: http://jsfiddle.net/Y4fHD/1/
var endCoords = {};
$(document.body).bind("touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});
And then use the variable endCoords
to determinate the last touch
$(document.body).bind("touchend", function(event) {
$('p').text("Your end coords is: x: " + endCoords.pageX + ", y: " + endCoords.pageY);
});
Ok try to just tap your device! Then the error still will ocure: Why? Because you havn't moved your touch.
If we all ready in the touchstart
defines the endCoords
variable we are there: http://jsfiddle.net/Y4fHD/2/
var endCoords = {};
$(document.body).bind("touchstart touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});
And then use the variable endCoords
to determinate the last touch
$(document.body).bind("touchend", function(event) {
$('p').text("Your end coords is: x: " + endCoords.pageX + ", y: " + endCoords.pageY);
});
Now try to tap your device!
Some final notes will be: Make to variables: startCoords
and endCoords
then use these in the touchend
event: http://jsfiddle.net/Y4fHD/3/
var startCoords = {}, endCoords = {};
$(document.body).bind("touchstart", function(event) {
startCoords = endCoords = event.originalEvent.targetTouches[0];
});
$(document.body).bind("touchmove", function(event) {
endCoords = event.originalEvent.targetTouches[0];
});
$(document.body).bind("touchend", function(event) {
$('p').text("Your touch on the axis: " + Math.abs(startCoords.pageX-endCoords.pageX) + "x, " + Math.abs(startCoords.pageY-endCoords.pageY) + "y");
});
Note:
None of the above examples are tested, hopes it works!
Math.abs
gives me the absolute value of a number eg: -5 becomes 5