Sagi_Avinash_Varma Sagi_Avinash_Varma - 2 months ago 6
CSS Question

html5 drag and drop using jquery (not jquery UI)

I want to implement the w3schools EXAMPLE for html5 drag and drop using jquery instead of javascript.

here is my implementation in jquery JSFIDDLE

I just changed the html inline declaration of events into jquery on() method keeping everything else same.

I cant understand why jquery doesnt recognize the events like drop dragstart when i see lot of snippets online.

HTML:

<div id="div1"></div>
<img id="drag1" src="http://www.w3schools.com/html/img_logo.gif" draggable="true" width="336" height="69">


JQUERY:

$(document).ready(function(){
$("#div1").on("dragover",function(e){
e.preventDefault();
});
$("#drag1").on("dragstart",function(e){
e.dataTransfer.setData("Text",ev.target.id);
});
$("#div1").on("drop",function(e){
e.preventDefault();
var data=e.dataTransfer.getData("Text");
e.target.appendChild(document.getElementById(data));
});
});

Answer

You want to use orginal event, not jQuery one to get/set data:

e.originalEvent

Fixed jsFiddle

$(document).ready(function(){
  $("#div1").on("dragover",function(e){
    e.preventDefault();
  });
  $("#drag1").on("dragstart",function(e){
    e.originalEvent.dataTransfer.setData("Text",e.target.id);
  });
  $("#div1").on("drop",function(e){
    e.preventDefault();
    var data=e.originalEvent.dataTransfer.getData("Text");
    e.target.appendChild(document.getElementById(data));
  });
});