Tutorial for HTML5 drag&drop - sortable list

html, javascript

Solution

I've tried to keep this sample as simple as possible.

If you create a HTML list:

<ul>
  <li draggable="true" ondragover="dragOver(event)" ondragstart="dragStart(event)">Apples</li>
  <li draggable="true" ondragover="dragOver(event)" ondragstart="dragStart(event)">Oranges</li>
  <li draggable="true" ondragover="dragOver(event)" ondragstart="dragStart(event)">Bananas</li>
  <li draggable="true" ondragover="dragOver(event)" ondragstart="dragStart(event)">Strawberries</li>
</ul>

...and the following javascript:

var _el;

function dragOver(e) {
  if (isBefore(_el, e.target))
    e.target.parentNode.insertBefore(_el, e.target);
  else
    e.target.parentNode.insertBefore(_el, e.target.nextSibling);
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move";
  e.dataTransfer.setData("text/plain", null); // Thanks to bqlou for their comment.
  _el = e.target;
}

function isBefore(el1, el2) {
  if (el2.parentNode === el1.parentNode)
    for (var cur = el1.previousSibling; cur && cur.nodeType !== 9; cur = cur.previousSibling)
      if (cur === el2)
        return true;
  return false;
}

... you should get a sortable list.

You can try the code on https://codepen.io/crouchingtigerhiddenadam/pen/qKXgap

Please be aware of the following bug in FireFox: https://developer.mozilla.org/en-US/docs/Web/Events/dragenter

Hope this helps.

Problem

Do anyone know a really good tutorial for HTML5 drag&drop? Im making a toDo-list and I want to be able to reorder/sort it with this API. I've been googling for it like a mad man and now im start giving up... ANY tips is welcomed! Thanks! p.s I really want to use html5 drag&drop API, not jQuery-sortable()

Original source