mmm
mmm

Reputation: 2297

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

Upvotes: 10

Views: 14300

Answers (4)

MightZ
MightZ

Reputation: 21

You can just check if event is cancelable. It's false after touchmove

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

Upvotes: 2

Derry White
Derry White

Reputation: 86

where you have dragging check put

if (dragging == true){
   dragging = false;
}

else{
$('.items').removeClass('selected');
$(this).addClass('selected');
}

it will reset it on release

also watch out for double calls on events as they sometimes trigger twice on some platforms best to check platform with first the following will help with checks

var clickEventType=((document.ontouchstart!==null)?'click':'touchend');

or

var clickEventType = 'touchend';
if(document.ontouchstart!==null)
{
     clickEventType = 'click';
}

Upvotes: 0

Jonathan
Jonathan

Reputation: 2983

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

Upvotes: 25

What have you tried
What have you tried

Reputation: 11138

You want to use either of the following:

if(dragging == true)

Or, simply:

if(dragging)

You should only use a single = sign when you are setting a value, whereas two == signs should be used when checking a value. Therefore, your code should look like:

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

Notice how you do not need to check if dragging == true because you are not running any code in this case. Instead you can simply check if dragging == false or, !dragging

Upvotes: 7

Related Questions