javascript - Uncaught TypeError: Cannot read property 'pageX' of undefined - Stack Overflow

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

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 ment in the if in touchmove, the coordinates popup. However, if it is mented, the error in my logcat appears.

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 ment in the if in touchmove, the coordinates popup. However, if it is mented, the error in my logcat appears.

Share Improve this question edited May 13, 2014 at 8:11 Bhushan Kawadkar 28.5k5 gold badges39 silver badges60 bronze badges asked May 13, 2014 at 8:01 JeongbebsJeongbebs 4,1207 gold badges35 silver badges62 bronze badges 2
  • First of all, the ments 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 Commented May 13, 2014 at 8:07
  • so I should change it to changedtouches? – Jeongbebs Commented May 13, 2014 at 8:09
Add a ment  | 

1 Answer 1

Reset to default 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744188533a4562321.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信