Detecting a Swipe Gesture
Calculate the direction and distance of a touch move to determine if a swipe gesture has occurred.
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;
// Set up the touch event listeners
const setupSwipeListeners = (element) => {
element.addEventListener('touchstart', handleTouchStart, false);
element.addEventListener('touchmove', handleTouchMove, false);
};
// Store the starting x and y coordinates of touch
function handleTouchStart(event) {
touchStartX = event.touches[0].clientX;
touchStartY = event.touches[0].clientY;
}
// Calculate the distance and direction of the swipe
function handleTouchMove(event) {
touchEndX = event.changedTouches[0].clientX;
touchEndY = event.changedTouches[0].clientY;
const diffX = touchEndX - touchStartX;
const diffY = touchEndY - touchStartY;
if (Math.abs(diffX) > Math.abs(diffY)) {
// Horizontal swipe
console.log('Swipe direction: ' + (diffX > 0 ? 'right' : 'left'));
} else {
// Vertical swipe
console.log('Swipe direction: ' + (diffY > 0 ? 'down' : 'up'));
}
}
// Example usage
// Pass the element you want to detect swipe on
setupSwipeListeners(document.querySelector('your-swipeable-element-selector'));
This code sets up event listeners for touchstart and touchmove events on a given element to detect swipe gesture direction. The handleTouchStart function records the initial touch position, and the handleTouchMove function calculates the swipe direction by comparing the end touch position with the start position. If the horizontal distance is greater than the vertical distance, it's considered a horizontal swipe; otherwise, it's a vertical swipe.