When I attempt to create a sortable list with HTML5 Drag n Drop, the target of the drop event (e.target
) is the child of the drop-zone element, rather than the drop-zone element itself. This is bad.
I want the value of e.target
in the following code to be the div
which contains ondrop="drop(event)"
rather than it's <p>
child.
Link to JSFiddle with full example.
function drop(e) {
e.preventDefault();
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(data));
}
Is this happening because of event bubbling, or something similar? What is the best fix that will help me create a Drag n Drop sortable list?
Edit: I am looking to understand the native HTML5 and Javascript, not use a jQuery library or some such.
You are trying to append to the target element, hence you are facing the problem.
You should try to insert the element before the target element.
function drop(e) {
e.preventDefault();
var data = e.dataTransfer.getData("text");
var list = document.getElementById("list");
list.insertBefore(document.getElementById(data), e.target.parentNode);
}
Here is the updated fiddle