Drag to mobile devices with a code that translates the event (including the code), but normal events do not work

I use the code below to enable touch drag and drop on my website. However, although parts of my code that have the drag and drop feature work on the iPhone, I still cannot scroll or move the page. I can drag and drop, but the usual iPhone features do not work!

I found the snippet below in a few stack overflow answers, so I'm wondering if there is a workaround for this. I want to be able to drag and drop both on the Internet and on mobile devices.

My drag and drop 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);    
}
+5
2

, . touchHandler , <div id='stage'>. jquery. , !

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();
  });
}
+1

:

event.preventDefault();

, .

, ( , , , ).

:

function init()
{
   document.addEventListener("touchstart", touchHandler, true);
   document.addEventListener("touchmove", touchHandler, true);
   document.addEventListener("touchend", touchHandler, true);
   document.addEventListener("touchcancel", touchHandler, true);    
}

To:

function init()
{
   $('#sortable_container').bind('touchstart touchmove touchend touchcancel', touchHandler); 
}
0

All Articles