Cancel touchend if touchmove fires

EmmaGamma picture EmmaGamma · Apr 25, 2013 · Viewed 12.2k times · Source

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');
    }
});

Answer

Jonathan picture Jonathan · Sep 17, 2014

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;
});