JavaScript

Swipe Events on Touch Devices in JavaScript

Last updated: 21.02.2026
Views: 270

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);
})();
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image
Refresh

*