Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag drop on mobile devices using some code that translates event (code included), but normal events are not working

I am using the below code to allow for touch drag and drop on my website. However, while the parts of my code which have drag/drop functionality work, on an iPhone, I cannot scroll or move the page in anyway. I can drag & drop, but regular iPhone touch functionality is gone!

I have found the below snippet in several Stack Overflow responses so I am wondering if there is a workaround for this. I want to be able to drag & drop on both web and mobile.

My dragging code (just a list):

$(function() {
    $(".drag_me ul").sortable();
});

code for touch events:

function touchHandler(event)
{
 var touches = event.changedTouches,
    first = touches[0],
    type = "";

     switch(event.type)
{
    case "touchstart": type = "mousedown"; break;
    case "touchmove":  type="mousemove"; break;        
    case "touchend":   type="mouseup"; break;
    default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
                          first.screenX, first.screenY,
                          first.clientX, first.clientY, false,
                          false, false, false, 0/*left*/, null);

first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}

function init()
{
   document.addEventListener("touchstart", touchHandler, true);
   document.addEventListener("touchmove", touchHandler, true);
   document.addEventListener("touchend", touchHandler, true);
   document.addEventListener("touchcancel", touchHandler, true);    
}
like image 538
Ringo Blancke Avatar asked Nov 14 '22 14:11

Ringo Blancke


1 Answers

I've been working on the same problem and think I just licked it. I removed the guts of touchHandler and use them to populate the callback that binds the event listeners only to the children of <div id='stage'>. Below is my code using jquery. Hope this helps!

function init(){


 $("#stage").children().bind('touchstart touchmove touchend touchcancel', function(){
    var touches = event.changedTouches,    first = touches[0],    type = ""; 
    switch(event.type){    
      case "touchstart": type = "mousedown"; 
    break;    
      case "touchmove":  type="mousemove"; 
    break;            
      case "touchend":   type="mouseup"; 
    break;    
      default: return;
    }

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                      first.screenX, first.screenY,
                      first.clientX, first.clientY, false,
                      false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
  });
}
like image 81
joatis Avatar answered Jan 26 '23 00:01

joatis