9

Here it is my dragstart:

dragstart: function(e) {
    $(this).css('opacity', '0.5');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('application/json', {
        id: $(this).attr('id'),
        header: $('header', this).text()
    });
},

I would like to pass some informations such id and text. My drop is:

drop: function(e) {
    var data = e.dataTransfer.getData('application/json');
    alert(data);
    $(this).attr('id', data.id);
    $('header', this).text(data.header);
},

But data is undefined, I can't access to my data. Is it the right way?

Thank's!

Syl
  • 2,232
  • 8
  • 34
  • 45
  • Could it be related to this? http://stackoverflow.com/questions/7640234/jquery-ui-draggable-droppable-datatransfer-is-undefined – ShivangiBilora Jan 30 '15 at 07:41

2 Answers2

13

in drag start

var testjson = {name:"asd",tall:123};
e.dataTransfer.setData("text/plain",JSON.stringify(testjson));
e.dataTransfer.effectAllowed = "copy";

in drop

var data = e.dataTransfer.getData("text/plain");
console.log(JSON.parse(data));

and u will get

Object {name: "asd", tall: 123} 

in console.log

Stupidfrog
  • 2,042
  • 6
  • 25
  • 35
  • This however allows the user to drop the json-string on any -Element by default, which might not be intended. – user2483352 Jun 17 '18 at 12:30
  • 2
    It would be more convenient if there was a way to pass the actual json object. It's a shame that you have to stringify it. – Nic Scozzaro Dec 10 '19 at 22:44
-1

If you include an effectAllowed in your dragstart function, such as:

e.dataTransfer.effectAllowed = 'move';

Then it is my understanding that you need to define an equivalent dropEffect in the drop function :

e.dataTransfer.dropEffect = 'move';
lukejacksonn
  • 475
  • 6
  • 9