Herm Luna Herm Luna - 3 months ago 14
Javascript Question

How to force stop touchmove in javascript?

Here's what I created.

var foo = document.getElementsByTagName('footer')[0],
startX = 0,
startY = 0,
finalX = 0,
finalY = 0;

function handleTouchStart(e){
var touch = e.touches[0] || e.changedTouches[0];

startX = touch.pageX;
startY = touch.pageY;
}

function handleTouchMove(e){
var touch = e.touches[0] || e.changedTouches[0],
touchX = startX - touch.pageX;

finalX += (touchX / 6);

foo.style.marginLeft = finalX + 'px';

if(Math.abs(touchX) >= 50){
e.preventDefault(); // not working
// stop touchmove if possible (So, touchend will be triggered)
// animate in touchend
}
}

function handleTouchEnd(e){
var touch = e.touches[0] || e.changedTouches[0],
getTouch = startX - touch.pageX;

if(getTouch < 0){
console.log('Swiping right: ' + getTouch);
} else {
console.log('Swiping left: ' + getTouch);
}
}

foo.addEventListener('touchstart', handleTouchStart, false);
foo.addEventListener('touchend', handleTouchEnd, false);
foo.addEventListener('touchmove', handleTouchMove, false);


Basically, I just want to stop the touchmove so I can animate the element. I'd search my problem but unluckily, I don't get any solutions.

Note: I didn't use jQuery because I'm creating a performance-based applications.

Any advice/help would be appreciated. Thanks!

wes wes
Answer

You cannot force a touchEnd event -- that is a default browser behaviour. However, you can work around this in your code by checking the offset of touchX first, and taking appropriate action if it exceeds the threshold:

function handleTouchMove(e){
    var touch = e.touches[0] || e.changedTouches[0],
        touchX = startX - touch.pageX;

    if(Math.abs(touchX) >= 50){
        e.preventDefault();
        console.log('breaking');
        handleTouchEnd(e);
        return;
    }

    ...

https://jsfiddle.net/mL76a9pe/1/

Comments