VuNguyen – 12-59 Mar 4

Hey, how do I check if user is swiping up or down using JS? Here is my attempt: Store the initial touchY in onTouchStart, then compare the initial touchY to touchY in onTouchMove. if current touchY is larger than initial touchY then it is considered that the user is swiping down, otherwise swiping up. The problem is, if user swiping down, but decide to swipe up, it stills count as swiping down, because the current touchY still larger than initial touchY
let initialTouchY = 0;

const handleTouchStart = (e) => {
initialTouchY = e.touches[0].clientY;
};

const handleTouchMove = (e) => {
const currentTouchY = e.touches[0].clientY;

if (currentTouchY > initialTouchY) {
// Swiping down, but if while user swiping down suddenly swipe up, it still counts as swiping down, and this code block executed
} else {
// Swiping up
}
}
let initialTouchY = 0;

const handleTouchStart = (e) => {
initialTouchY = e.touches[0].clientY;
};

const handleTouchMove = (e) => {
const currentTouchY = e.touches[0].clientY;

if (currentTouchY > initialTouchY) {
// Swiping down, but if while user swiping down suddenly swipe up, it still counts as swiping down, and this code block executed
} else {
// Swiping up
}
}
How do I fix this problem. Thank you.
S
ScriptyChris411d ago
Shouldn't initialTouchY be rather recentTouchY and track only last touch movement? So you would compare only against last swipe, not initial one to every subsequent @VuNguyen Also, this variable should be a state, because otherwise (as currently) at every componenr render it will be 0 again
N
Nguyen411d ago
Sorry I wrote the question wrong, it should be dragging, not swiping
S
ScriptyChris411d ago
Same scenario i guess Is it React?
N
Nguyen411d ago
I'm talking about the case the when user dragging down (the touch not yet ended), and suddenly drag up, it still counts as dragging down no it is js im writing it in react but im asking it in js I actually found the solution, we will store the current touchY to moveYTouch as we dragging them, then compare current touchY to moveYTouch instead of initialYTouch
UU
Unknown User411d ago