Home › Forums › JavaScript › Detect vertical direction of jQuery touchmove? › Reply To: Detect vertical direction of jQuery touchmove?
Worked a bit on the last snippet and got a solution. The problem was that lastY value wasn’t always accurate. On the first touch it returned an undefined value. Then on the second swipe, lastY returned the last position of the previous swipe. These two conditions caused an incorrect reading of the movement when we compared lastY and currentY.
The solution is to grab lastY in the ‘touchstart’ instead of ‘touchmove’, where we will only grab currentY:
var lastY,
timer;
$(document).bind(‘touchstart’, function(e) {
lastY = e.originalEvent.touches ? e.originalEvent.touches[0].pageY : e.pageY;
console.log(lastY);
});
$(document).bind(‘touchmove mousemove’, function(e) {
var currentY = e.originalEvent.touches ? e.originalEvent.touches[0].pageY : e.pageY;
//console.log(“CurY: “+currentY+” / LasY: “+lastY);
if (Math.abs(currentY-lastY) < 15) { return; }
if (currentY > lastY) {
console.log(‘down’);
} else {
console.log(‘up’);
}
});