htmljqueryconflicttouchstart

jQuery conflict between touchstart/touchend with normal click in mobile screen


The click normal on image is not fired, I have a conflict with the touchstart/touchend commands in mobile device android.

The delay function is for show to alert after 5 seconds. But cancel if it does not reach 5 seconds.

Touchstart start function and touchend clear setTimeout for cancel function.

The normal click over image not fired.

What is the error?

let myTimeout;
var mousedownFired = false;
    
$(document).on("touchstart", "figure img", (e) => { // Start setTimeout with Delay
    e.preventDefault();
            
    mousedownFired = true;
      
      myTimeout = setTimeout(function() {
          console.log("PRESS WITH DELAY");
    }, 5000);
});
$(document).on("touchend", "figure img", (e) => { // Cancel setTimeout
    e.preventDefault();
  
    clearTimeout(myTimeout);
    console.log("STOPING!");
    //e.stoppropagation();
});
$(document).on("click", "figure img", (e) => {
    e.stopPropagation();
    e.preventDefault();
        
    if (mousedownFired) {
        mousedownFired = false;
        console.log("CLICK IMG NORMAL");
        return;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section>
  
  <figure>
  <img id="demo" src="https://picsum.photos/536/354" />
  </figure>
  
</section>


Solution

  • That's what Pointer Events are made for - To have a single code-base for both mouse and touch pointers.

    let myTimeout;
    
    const handleDown = (evt) => {
      evt.preventDefault();
      console.log("PRESSED");
      myTimeout = setTimeout(function() {
        console.log("PRESSED WITH DELAY");
      }, 1000);
    };
    
    const handleUp = (evt) => {
      clearTimeout(myTimeout);
      console.log("STOPPED!");
    };
    
    $(document)
      .on("pointerdown", "figure img", handleDown)
      .on("pointerup", "figure img", handleUp);
    <figure>
      <img src="https://picsum.photos/536/354" />
    </figure>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    PS:

    Never use (unless for debugging purposes) Event.stopPropagation(). At any time an app (or third-party scripts) should be able to register events that occur in its environment document - without exceptions, in order to respond and act properly. Imagine just for example a script for modals, or for custom select boxes, popups... If a script of yours used stopPropagation() the modals would not close as expected.