Search code examples
jqueryonclickswipetouch-event

Prevent click events from executing after a touch event


Simply explained I have this code:

$(".button").swipe({
    swipe: function () {
        $("#output").append("You swiped!");
    }
}).click(function () {
    $("#output").append("You clicked!");
});

I want to be able to handle swipe on my element (TouchSwipe plugin) and clicks. The problem is that a touch is also a click. So if I swipe, I will first get "You swiped!" followed by a "You clicked!". Just clicking is ok.

Is it possible to stop the .click() from being executed if the .swipe() has already been executed? This, of course, has to work each time.


Solution

  • Based on the implementation you supplied is with I'm guessing you are using the jQuery TouchSwipe plugin, correct?

    Right, you noted you were using the jQuery TouchSwipe plugin, my bad :)

    Instead of the jQuery click event (which does not take into account other plugin events) you should use the TouchSwipe tap event. This implementation helps distinguish the click from the swipe event and helps making sure only one gets executed.

    jQuery(function()
    {
        jQuery('.button').swipe({
            tap: function()
            {
                alert('tapped');
            },
            swipe: function(event, direction, distance, duration, fingerCount)
            {
                alert('swiped');            
            }
        });
    });
    

    demo: http://jsfiddle.net/bsmayh1q/