Swipe Events on Touch Devices in JavaScript
Every day sensory devices are being introduced into our lives. These devices have specific events, unlike the desktop. One of these events is the swipe. Especially often have to deal with it when developing a mobile version of the site.
Swipe events on touch devices allow developers to detect gestures like swiping left, right, up, or down, commonly used for navigation or interaction. These events can be implemented by tracking the touchstart, touchmove, and touchend events in JavaScript. By capturing the starting touch position (touchstart) and comparing it to the ending position (touchend), you can calculate the swipe direction and distance.
For example, a swipe left occurs when the horizontal distance between the start and end points is negative and exceeds a defined threshold. Similarly, you can check for vertical swipes by comparing the Y-axis values.
Code:
(() => {
let initialPoint;
let finalPoint;
document.addEventListener('touchstart', function(event) {
initialPoint = event.changedTouches[0];
}, false);
document.addEventListener('touchend', function(event) {
finalPoint = event.changedTouches[0];
let xAbs = Math.abs(initialPoint.pageX - finalPoint.pageX);
let yAbs = Math.abs(initialPoint.pageY - finalPoint.pageY);
if (xAbs > 20 || yAbs > 20) {
if (xAbs > yAbs) {
if (finalPoint.pageX < initialPoint.pageX) {
// to left
} else {
// to right
}
} else {
if (finalPoint.pageY < initialPoint.pageY) {
// to top
} else {
// to down
}
}
}
}, false);
})();
Similar posts:
-
How to Сlone (Copy) Object and Array in JavaScript
Cloning objects and arrays is not as simple a topic as it may seem at first glance. Cloning objects and arrays in JavaScript can be done using various methods depending...
-
How to Get Max Value in JavaScript Array
A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. To find the maximum va...
-
Countdown Timer in JavaScript
Often on sites that sell something, you can find a countdown timer to a certain date. Such a script is usually needed for landing pages or online stores. In one of the pr...
Leave a Reply