HTML5 drag and drop for MOBILE

I found this drag and drop code in w3schools that works on the desktop but not on mobile devices.

What do I need to change so that it recognizes the touch?

<!DOCTYPE HTML> <html> <head> <style type="text/css"> #div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;} </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <p>Drag the W3Schools image into the rectangle:</p> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br> <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </body> </html> 
+7
javascript jquery html5 mobile drag-and-drop
source share
1 answer

Most mobile devices do not listen to drag and drop events associated with the DOM. I would recommend using the touchmove event and the events that come with it. It would look like this:

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="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> 

handleStart, handleEnd, etc. - these are your callbacks that are fired from an event where you can handle the touch event.

If you don’t want to do all the heavy lifting before touching, then I would recommend a library like JQuery Touch Punch. I used it and it works great on iOS.

Here is a link to the library where you can also test your performance on your mobile device: http://touchpunch.furf.com/

OPTION 2 (BEST OPTION) JQuery Touch punch is included as follows:

Enable jQuery and the jQuery user interface on the 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> 
+12
source share

All Articles