Javascript: detect swipes (touch + mouse)

Date: 2020-10-27
function getPosition(event) {
    if (event.touches && event.touches[0])
        return { x: event.touches[0].clientX  || 0, y: event.touches[0].clientY  || 0 };
    return { x: event.clientX || 0, y: event.clientY || 0 };
}

function getDiff(a, b) {
    const aa = getPosition(a);
    const bb = getPosition(b);
    return { x: bb.x - aa.x, y: bb.y - aa.y };    
}

function detectSwipes(el) {
    let firstMove = null;
    let lastMove = null;

    function start(event) {
        firstMove = lastMove = event;
    }

    function move(event) {
        lastMove = event;
        if (firstMove && lastMove) {
            console.log('drag', getDiff(firstMove, lastMove))
        }
    }
    function end(event) {
        if (firstMove && lastMove) {
            const diff = getDiff(firstMove, lastMove);
            const distX = Math.abs( diff.x );
            const distY = Math.abs( diff.y );
            if (distX > distY) {/* most significant */
                if ( diff.x > 0 ) { /* left swipe */ 
                    console.log('swipe left', distX);
                } else { /* right swipe */
                    console.log('swipe right', distX);
                }                       
            } else {
                if ( diff.y > 0 ) { /* up swipe */ 
                    console.log('swipe up', distY);
                } else { /* down swipe */
                    console.log('swipe down', distY);
                }                                                                 
            }
        }
        firstMove = null;
        lastMove = null;
    }

    el.addEventListener('mousedown', start, false);
    el.addEventListener('mousemove', move, false);
    el.addEventListener('mouseup', end, false);
    el.addEventListener('touchstart', start, false);
    el.addEventListener('touchmove', move, false);
    el.addEventListener('touchend', end, false);
}

const doc = document.documentElement;
doc.style.height = '100%';
doc.style.width = '100%';
doc.style.border = '3px solid red';
detectSwipes(doc);
41770cookie-checkJavascript: detect swipes (touch + mouse)