Question

I want to calculate the distance between the initial value of the touchstart and the actual value on touchmove.

for exemple :

I touch the screen : startX = 100; Then, I move my finger on the screen : moveX = 150;

The distance from startX and moveX is (moveX - startX) = 50;

CODE UPDATED :

function touch(event) {
var moveX = event.pageX;
var totalMoved = Math.abs(document.startX - moveX);
shipX = totalMoved;
consoleLog(totalMoved);
};

function touchStart(event) {
    touch(event.touches[0]);
    document.startX = event.pageX;
};

function touchMove(event) {
    event.preventDefault();
    touch(event.touches[0]);
}; 

function touchEnd(event) {
    touch(event.touches[0]);
    var totalMoved = 0;
}; 
Was it helpful?

Solution

Yes, this is possible. You just need to store the value in a scope that will be visible in your touchMove() function. For the sake of illustration, we can solve this problem by polluting the global scope:

function touchStart(event) {
    touch(event.touches[0]);
    window.startX = event.pageX;
};

function touchMove(event) {
    event.preventDefault();
    var moveX = event.pageX;
    var totalMoved = Math.abs(window.startX - moveX);
}; 

Of course, there are various ways to do this without polluting the global scope. For instance, you could make your event handler functions be members of some object that holds the necessary state as member variables. Or the touchStart() handler could create a closure that encapsulates the startX variable and then set that to be the touchesMoved handler. And so on.

OTHER TIPS

You moveXs are declared in different functions and hence denote different variables. Declare var moveX in the enclosing scope for all these functions instead (I guess you might want to do the same with startX).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top