Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 931
Syl Avatar asked Mar 02 '12 12:03

Syl


People also ask

What drag means in slang?

someone or something that is unpleasant and boring: Waiting in a doctor's office is such a drag!

Why do you mean by drag?

to draw with force, effort, or difficulty; pull heavily or slowly along; haul; trail: They dragged the carpet out of the house. to search with a drag, grapnel, or the like: They dragged the lake for the body of the missing man. to level and smooth (land) with a drag or harrow.


1 Answers

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

like image 121
Stupidfrog Avatar answered Oct 03 '22 04:10

Stupidfrog