Nguyen
Nguyen2y ago

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.
5 Replies
ScriptyChris
ScriptyChris2y 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
Nguyen
Nguyen2y ago
Sorry I wrote the question wrong, it should be dragging, not swiping
ScriptyChris
ScriptyChris2y ago
Same scenario i guess Is it React?
Nguyen
Nguyen2y 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
reactibot
reactibot2y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1081561636369870848