4

I am tinkering with touchevents in js. I have encountered this error in my logcat in eclipse.

document.getElementById("squareBracket").
    addEventListener("touchmove", touchHandler, false);
document.getElementById("squareBracket").
    addEventListener("touchend", touchHandler, false);

function touchHandler(e) {
 if (e.type == "touchstart") {
 alert("You touched the screen!");
  } else if (e.type == "touchmove") {
 // alert(e.changedTouches[0].pageX);
 // alert(e.changedTouches[0].pageY);
 } else if (e.type == "touchend" || e.type == "touchcancel") {
  alert('X :' + e.targetTouches[0].pageX); 
  alert('Y :' + e.targetTouches[0].pageY);
}
}

If I remove the comment in the if in touchmove, the coordinates popup. However, if it is commented, the error in my logcat appears.

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
Jeongbebs
  • 4,100
  • 7
  • 34
  • 60
  • First of all, the comments don't influence your logcat error. it seems e.targetTouches[0] is null or undefined. be aware it's `changedTouches` in first case and `targetTouches` in second case. – cosmincalistru May 13 '14 at 08:07
  • so I should change it to `changedtouches`? – Jeongbebs May 13 '14 at 08:09

1 Answers1

5

You should start understanding the difference of targetTouches, changedTouches and touches here: Variation of e.touches, e.targetTouches and e.changedTouches

in your case in the moment of touchend or touchcancel the targetTouches list is empty and the information remains in changedTouches.

changing your code to:

alert('X :' + e.changedTouches[0].pageX); 
alert('Y :' + e.changedTouches[0].pageY);

should do the trick.

Community
  • 1
  • 1
Dennis Meissner
  • 449
  • 3
  • 10
  • so I can save the start coordinates at `changedTouches[0]` and the end coordinates in `changedtouches[1]` ? Thanks. – Jeongbebs May 13 '14 at 08:24
  • Yes but you should always check if there are items available in your list of touches with if (e.changedTouches[0] && e.changedTouches[1]) { ... } just to make sure that there have been 2 touches. – Dennis Meissner May 13 '14 at 08:32
  • hey Dennis I added this code `if (e.type == "touchmove") { startX = e.changedTouches[0].pageX; startY = e.changedTouches[0].pageY; } else if (e.type == "touchend" || e.type == "touchcancel") { endX = e.changedTouches[0].pageX; endY = e.changedTouches[0].pageY; alert (startX + endX); }` It only shows the end coordinates, why is that? – Jeongbebs May 13 '14 at 08:43
  • You need to store your start coordinates in the touchstart event and use this stored coordinates + the changedTouches coordinates inside your touchend event. You need to track this yourself, javascript can't do this natively for you – Dennis Meissner May 13 '14 at 08:56