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 Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to detect the user’s operating system when building web applications or websites. This can be useful for applying different CSS styles, collecti...
-
How to Submit a Form Using jQuery Ajax ($.ajax)
Submitting a form using jQuery's $.ajax method is a powerful way to send data to the server without reloading the page. This approach improves user experience and allows ...
-
Drop down menu (jQuery)
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
Leave a Reply