Last Updated: May 31, 2021
·
9.464K
· steveambielli

Detecting Swipe Using jQuery

I've run into a situation where I needed to detect if the user swiped on the page and I didn't want to include a 3rd party jQuery plug-in. By just using the jQuery library, you can detect when a user swipes the page and do whatever you need accordingly.

$(function() {    
    $("#surface")
        .on('mousedown touchstart', function (e) {
            console.log("(x,y) = (" + e.pageX + "," + e.pageY +")");
            xDown = e.pageX;
            yDown = e.pageY;
        })
        .on('mouseup touchend',function (e) {
            console.log("(x,y) = (" + e.pageX + "," + e.pageY +")");
            xUp = e.pageX;
            yUp = e.pageY;
            if (xDown != xUp || yDown != yUp) {
                alert('Swiped');   
            }
        })
    ;    
})(jQuery);

1 Response
Add your response

this only works because in touchdown event it returns undefined

consider using 'e.originalEvent.touches[0]' for touchstart

and for touchend use 'e.originalEvent.changedTouches[0]'

over 1 year ago ·