- This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
Viewing 3 posts - 1 through 3 (of 3 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Detect vertical direction of jQuery touchmove?
Hello,
I’m attempting to detect the vertical direction of a jQuery touchmove event, but I can’t seem to figure out a solution.
The following bit works, but both the up/down directions have the same output.
$(document).on('touchmove', function(e) {
alert('works');
});
Ideally, I would like to use something like the following…
$(document).on('touchmove', function(e) {
if (deltaY > 0) {
alert('down');
} else {
alert('up');
}
});
I also came across this Stack Overflow thread, but It doesn’t seem to be a plausible solution. Any help is appreciated.
Thanks
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’);
}
});
Here’s a solution as well :