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?
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
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.
In HTML5, drag and drop is part of the standard: Any element can be draggable. You can refer below link: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.