1
votes

Lately I've started playing with touch events in javascript and I encountered a strange problem with touchend event (propably something obvious and I'm just too dumb to understand it). So basically, here is my code:

function send(e) {
    e.preventDefault();
    document.body.innerHTML = e.type + "<br>" + e.targetTouches[0].pageY;
}

['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
    window.addEventListener(e, send, false);
});

And now the e.targetTouches[0].pageY works fine, but the e.type will only assume touchstart or touchmove value, not the touchend for some reason. I noticed that it only happens when I try to call the e.type property in the same line or after reading any property from the event.targetTouches (or event.touches) array. Aren't those properties read-only? Why does it brake my code?

Oh, and after few hours of playing with it I noticed that the event.type will assume the touchend value only when holding one finger on the screen and then tapping it with another, still that doesn't solve my problem,.

1

1 Answers

6
votes

This is because touchend event is fired when touch point is removed.

No touch point, no targetTouches.

MDN TouchEvent.targetTouches

A TouchList listing all the Touch objects for touch points that are still in contact with the touch surface

MDN touchend

The touchend event is fired when a touch point is removed from the touch surface

To solve your problem, recording the targetTouches when touchstart and touchmove, and use it when touch point is removed:

var TargetTouches;

function send(e) {

    e.preventDefault();

    var type = e.type;
    var pageY;

    if (type !== 'touchend') {
      pageY = e.targetTouches[0].pageY;
      TargetTouches = e.targetTouches[0];
    } else {
      pageY = TargetTouches.pageY;
    }

    document.body.innerHTML = type + "<br>" + pageY;
}

['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
    window.addEventListener(e, send, false);
});