Explain Codes LogoExplain Codes Logo

Detect a finger swipe through JavaScript on the iPhone and Android

javascript
touch-events
gesture-detection
mobile-devices
Nikita BarsukovbyNikita Barsukov·Oct 17, 2024
TLDR
// Setup the usual suspects: Touch event listeners document.addEventListener("touchstart", handleTouchStart, false); document.addEventListener("touchmove", handleTouchMove, false); let xDown = null, yDown = null; // It's not magic, it's return key. Get initial touch coordinates. function handleTouchStart(evt) { const { clientX, clientY } = evt.touches[0]; xDown = clientX; yDown = clientY; } // Finger dance tracker. Calculate and determine swipe direction. function handleTouchMove(evt) { if (!xDown || !yDown) return; // Exit if coordinates are not available const { clientX, clientY } = evt.touches[0]; const xDiff = xDown - clientX, yDiff = yDown - clientY; // Using advanced math to figure out if it was a horizontal or vertical swipe. if (Math.abs(xDiff) > Math.abs(yDiff)) { console.log(xDiff > 0 ? "It's a **Left** swipe, not a romance novel" : "No right turn, **Right** swipe"); } else { console.log(yDiff > 0 ? "**Up** swipe, just like your mood now" : "**Down** swipe, like my bad jokes"); } // Reset, just like your router xDown = yDown = null; }

Single taps vs swipes

Differentiating between single taps and swipes can be achieved by combining with touchend events and setting some time logic. Set a few criteria like travel distance and time limit. This way, you prevent accidental detection of swipes when the user merely wanted to tap the screen.

Consider different devices

Different browsers and devices interpret touch events differently. Always test your implementation across various environments to ensure consistency in user experience. This includes considering browser prefixes and the presence of differing touch properties.

Handle swipes with libraries

The swiped-events.js library is a great resource available on GitHub for detecting swipes and customizing the threshold for swipe detection. Using this library ensures you have consistent swipe detection across different devices.

Swipe detection across devices and browsers

The Swipe class from swiped-events.js can be used to specify callbacks for swipes in different directions, making the code more organized. This helps to ensure your swipe detection is compatible on both iPhone and Android devices across different browsers.

Visualizing swipe detection

Swiping a touch screen is like moving a physical object.

Starting Point: 🖐 touchstart In Motion: ➡️➡️➡️ (move) Ending Point: 🛬 touchend

Meet specific criteria to be considered a Swipe?

if (distanceTraveled > threshold && timeTaken < timeLimit) { // 🎯 It's successfully recognized as a swipe gesture! }
🖐⏱️➡️➡️➡️🛬🎯 # A recognized swipe gesture involves timing from start to finish, # moving a certain distance within a limited timeframe.

Cross-browser swipe functionality

Ensure gesture detection functions across a range of browsers. Test on different browsers like Chrome and Safari on both iOS and Android platforms to verify the code works effectively.

jQuery implementation for swipe detection

In a jQuery environment, you may opt to refer to event.originalEvent.touches for a reliable read on touch points. You can then decide swipe direction by calculating changes in the x and y coordinates.

Enhancing gesture interaction

To provide an accurate gesture interaction, don't forget to consistently test and refine your code based on user feedback. This will lead to a more precise subsequent swipe detection and a much better user experience.