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:
-
jQuery Tabs Plugin
Tabs are a fairly common element. There are various implementations of this element on the Internet. But often the tabs are overloaded with code filled with effects that ...
-
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...
-
Ways to Create Objects in JavaScript
There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain ot...
Leave a Reply