2

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.

Ben
  • 5,085
  • 9
  • 39
  • 58
  • 1
    I guess [this answer](http://stackoverflow.com/a/18542687) does explain a bit about the issue – anpsmn Apr 10 '15 at 05:43
  • Your link helped my understand the problem. Here's the quote from your link that pulled it all together: "Because the `dragenter` event is fired on child nodes before the `dragleave` event on the parent". – Ben Apr 10 '15 at 05:56

1 Answers1

0

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

Kiran Reddy
  • 556
  • 3
  • 11
  • Your answer solves my problem, but why is the `

    ` tag considered a drop-zone when only the parent `

    ` has the drop-zone code? (`ondragover="allowDrop(event)"`)
    – Ben Apr 10 '15 at 05:58
  • Also, is this a correct implementation of the HTLM5 drag and drop standard? Or is it hacky and incorrect in some way? – Ben Apr 10 '15 at 06:02
  • a. After you read Quirksmode's [post](http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html) on HTML5 drag and drop, you are wary about touching it at all. b. `e.target` is still the child node - we're just working around that c. Every other post about sortable HTML5 drag and drop lists contains about 10x more code, so that gets me worrying. What are your thoughts? – Ben Apr 10 '15 at 06:13
  • It simply works but you included jquery in your jsfiddle example, while it is not in use. Misleading for beginners! – NVRM Apr 08 '19 at 00:36