Benjamin Benjamin - 1 month ago 18
Javascript Question

Drag and drop div in HTML5

I try to drag and drop a div element (call it A) in a box B which is a another div. I would like to append an new div A in B each time I drop A in B.

Actually I have something like this:

function handleDragStart(e) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('application/x-moz-node', e.target);
}


function handleDrop(e) {
//stuff
this.append(e.dataTransfer.getData('application/x-moz-node'));
return false;
}


But when I drop A in B: [object HTMLDivElement] is appended in B instead of A.

Could you tell me where I am wrong and is it the good way to do this?

Answer

There are numerous issues with setData and getData and the cross-browser compatibility. You should only rely on the dumb old text/plain

I would advise you to just pass the id of the div A and then:

function handleDragStart(e) {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', e.target.id);
}

function handleDrop(e) {
    var a = document.getElementById(e.dataTransfer.getData('text/plain'));
    a = a.cloneNode(true);
    a.id = "a new id here otherwise it is duplicated id";
    this.appendChild(a);

    e.preventDefault();
}

https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode