html5 drag and drop FOR MOBILE [duplicate]

Most mobile devices do not listen to the drag events that are bound to the DOM. I would recommend using the touchmove event and the events that go along with with it. It would look something like:

OPTION 1

 <!DOCTYPE HTML>
 <html>
 <head>
 <style type="text/css">
       #div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
 </style>
 </head>
 <body>

 <p>Drag the W3Schools image into the rectangle:</p>

 <div id="div1"></div>
 <br>
 <img id="drag1" src="https://stackoverflow.com/questions/20927759/img_logo.gif width="336" height="69">

 <script type="text/javascript">
  var el = document.getElementById('drag'); 

  el.addEventListener("touchstart", handleStart, false);
  el.addEventListener("touchend", handleEnd, false);
  el.addEventListener("touchcancel", handleCancel, false);
  el.addEventListener("touchleave", handleEnd, false);
  el.addEventListener("touchmove", handleMove, false);

  function handleStart(event) {
      // Handle the start of the touch
  }

  // ^ Do the same for the rest of the events

</script>
</body>
</html>

The handleStart, handleEnd, etc. are your callbacks that are fired from the event, which is where you can handle touch event.

If you don’t want to do all of the heavy lifting as far as the touch events, then I would recommend a library such as JQuery Touch Punch. I’ve used it and it works very well on iOS.

Here’s a link to the library where you can also test out its performance in your own mobile device: http://touchpunch.furf.com/

OPTION 2 (BETTER OPTION)
JQuery Touch punch is included like so:

Include jQuery and jQuery UI on your page.

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script>

// Download this from the link above
<script src="jquery.ui.touch-punch.min.js"></script>

<script>
    $('#drag1').draggable();
    $( "#div1" ).droppable({
        drop: function( event, ui ) {
          $( this )
            .addClass( "isDropped" )
            .html( "Dropped!" );
        }
      });
    });

</script>

Leave a Comment