Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }
});
like image 298
heckascript Avatar asked Apr 25 '13 02:04

heckascript


3 Answers

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;
});
like image 121
Jonathan Avatar answered Nov 13 '22 10:11

Jonathan


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

like image 7
What have you tried Avatar answered Nov 13 '22 11:11

What have you tried


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');
    }
});
like image 1
MightZ Avatar answered Nov 13 '22 11:11

MightZ