Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent swipe to trigger click?

I use TouchSwipe to create a swipeable image list. I bind the swipe event to the images, while I also bind a click event that will open up the image's large version.

My problem is that if I swipe, it also fires the click event. I tried tap instead of swipe but I can't make it work. After this I tried event.preventDefault() and event.stopPropagation() that was suggested in a lot of place, but there was no effect. My final solution attempt was to unbind the click event and rebind it after the event, but if I bind the event in the very end of the event function, it fires click again.

$(".js-header-swipe-image").swipe({
    swipe:function(event, direction, distance, duration, fingerCount){
        $("#details").unbind('click');//Temporary unbind, otherwise the swipe's click would trigger the gallery opening.

        //Handling swipe direction.

        $('#details').on('click', '.js-header-swipe-image', function (){//Rebind the temporary unbinded event.
            console.log('click');
            $('#modal-gallery').modal('show');
        });
    }
});

Is there a way to abort an event itself or call a function after the event finished so I can rebind the click after the swipe finished so it wouldn't trigger the rebinded click? I'm also open to any other solution to the problem.

like image 932
totymedli Avatar asked Oct 07 '13 14:10

totymedli


1 Answers

I use this bit of code so that buttons are only triggered (on touchend) if not being swiped on:

var startY;
var yDistance;

function touchHandler(event) {
    touch = event.changedTouches[0];
    event.preventDefault();
}

$('.button').on("touchstart", touchHandler, true);
$('.button').on("touchmove", touchHandler, true);

$('.button').on("touchstart", function(){
    startY = touch.clientY;
});

$('.button').on('touchend', function(){

    yDistance = startY - touch.clientY;

    if(Math.abs(yDist) < 30){

        //button response here, only if user is not swiping
        console.log("button pressed")
    }
});
like image 82
LocDog Avatar answered Oct 09 '22 06:10

LocDog