Drag & Drop HTML 5 jQuery: e.dataTransfer.setData () with JSON

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 convey some information of such identifier and text. My fall:

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

But the data is undefined, I can not access my data. Is it correct?

Thank you in!

+5
source share
2 answers

at the beginning of the drag

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

in folder

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

and u will get

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

in console.log

+9
source

If you included the Allowed effect in the dragstart function, for example:

e.dataTransfer.effectAllowed = 'move';

Then I understand that you need to define an equivalent dropEffect in the drop function:

e.dataTransfer.dropEffect = 'move';
0
source

All Articles