SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Drag and Drop

Drag and Drop

Build sortable lists and drag-and-drop interfaces using native HTML5 drag events handled with jQuery.

Example
let dragSrc = null;
$(".sortable-item").on("dragstart", function(e) {
  dragSrc = this;
  e.originalEvent.dataTransfer.effectAllowed = "move";
  e.originalEvent.dataTransfer.setData("text/html", this.outerHTML);
  $(this).addClass("dragging");
}).on("dragover", function(e) {
  e.preventDefault();
  e.originalEvent.dataTransfer.dropEffect = "move";
}).on("drop", function(e) {
  e.preventDefault();
  if (dragSrc !== this) {
    dragSrc.outerHTML = this.outerHTML;
    this.outerHTML = e.originalEvent.dataTransfer.getData("text/html");
  }
}).on("dragend", function() { $(this).removeClass("dragging"); });
Pro Tip

For complex drag-and-drop (multi-handle, touch support), use SortableJS or jQuery UI Sortable.