Swipe events on touch devices

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.

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);
})();

Comments

Popular posts from this blog

Typical gulpfile.js

JavaScript Inheritance and Classes

Cheat sheet for work with Git