javascriptjqueryclicktouch-eventtouchmove

Cancel touchend if touchmove fires


I'm building something mainly for use on tablets, where the user can tap an item on the screen and a class is applied to it. This is what I have so far:

The problems:

  1. I want to use touch events to remove the class and add the class on touch end (to make it faster).
  2. I don't want it to do anything if the user swipes (touchmoves).

I've tried a number of things, none of which have worked. The simplest I've tried (unsuccessfully) is this:

var dragging = false;

$(".items").on("touchmove", function(){
      dragging = true;
});

$('.items').on("click touchend", function(event){
    if (dragging = true){
    }
    else{
    $('.items').removeClass('selected');
    $(this).addClass('selected');
    }
});

Solution

  • I would argue this is a more safe way of doing it

    Setting variable to false

    var dragging = false;
    

    Setting var to true ontouchmove (allows you to reuse this code everywhere in your app)

    $("body").on("touchmove", function(){
      dragging = true;
    });
    

    Your button

    $("#button").on("touchend", function(){
          if (dragging)
          return;
    
          // your button action code
    });
    

    Resetting variable (important)

    $("body").on("touchstart", function(){
        dragging = false;
    });