How to detect swipe from Touch and Mouse and find swipe direction

1.6k Views Asked by At

I am trying to build a carousel using CSS and jQuery.

However, I want to add swipe events for easy user experience..

I found a code snippet promising swipes using mouse and touch.

After heavily Modifying it, I tried to use it for my Carousel...

It works on Mobile, but doesn't work on Desktop (tried on Windows 7, Google Chrome)

Here's the code

    document.addEventListener('touchstart', handleTouchStart, false);        
    document.addEventListener('touchmove', handleTouchMove, false);

    var xDown = null;                                                        
    var yDown = null;

    function getTouches(evt) {
        return evt.touches || evt.originalEvent.touches;
    }                                                     

    function handleTouchStart(evt) {
        console.log('start');
        const firstTouch = getTouches(evt)[0];                                      
        xDown = firstTouch.clientX;                                      
        yDown = firstTouch.clientY;                                      
    };                                                

    function handleTouchMove(evt) {
        console.log('move');
        if ( ! xDown || ! yDown ) {
            return;
        }

        var xUp = evt.touches[0].clientX;                                    
        var yUp = evt.touches[0].clientY;

        var xDiff = xDown - xUp;
        var yDiff = yDown - yUp;

        if ( xDiff > 0 ) {
            jQuery('.CarouselNext').click();    
        } else {
            jQuery('.CarouselPrevious').click();
        }                       
        xDown = null;
        yDown = null;                                             
    };

I read that for compatability with Mouse, I need to use mousestart and mousemove

I tried, to change the first 2 lines like this:

    document.addEventListener('mousestart', handleTouchStart, false);        
    document.addEventListener('mousemove', handleTouchMove, false);

It doesn't work...

Not even on Android/iOS

I am told that this is because, I am not able to find the swipe direction properly using mousestart.

Please suggest.

0

There are 0 best solutions below