Search code examples
javascriptjqueryiostouchtouch-event

checking if touchend comes after a drag


I have some code which changes the class of a table. On a phone, sometimes the table will be too wide for the screen and the user will drag/scroll about to see the contents. However, when they touch and drag the table around, it triggers touchend on every drag.

How do I test to see whether the touchend came as a result of a touch-drag? I tried tracking dragstart and dragend but I couldn't get that to work and it seems an inelegant approach. Is there something I could add to below which would essentially determine, "Did this touchend come at the end of a drag?"

$("#resultTable").on("touchend","#resultTable td",function(){ 
        $(this).toggleClass('stay');
});

My thanks in advance for your help.

PS - using latest jquery, and while a regular click works, it is very slow in comparison to touchend.


Solution

  • Use two listeners:

    First set a variable to false:

    var dragging = false;
    

    Then ontouchmove set dragging to true

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

    Then on drag complete, check to see if dragging is true, and if so count it as a dragged touch:

    $("body").on("touchend", function(){
          if (dragging)
              return;
    
          // wasn't a drag, just a tap
          // more code here
    });
    

    The touch end will still fire, but will terminate itself before your tap script is run.

    To ensure the next time you touch it isn't already set as dragged, reset it back to false on touch down.

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