Drag And Drop

Drag and drop is now part of HTML5


1
2
3
You can drag and drop an item in an empty area (hole)

  • Note

  • To specify to the browser that an element can be dragged, use the draggable attribute, which has three valid values: true, false, and auto.
    <div id="item1" class="item" draggable="true">1</div>

    The dragenter and dragover events default to rejecting dragged items, which is why you can’t currently drop an item. You can enable dropping by cancelling the default action on these events.
    e.preventDefault();

  • Drag Event

  • dragstart: Triggers when the drag is started
  • drag: Triggers continuously as the element is being dragged
  • dragend: Triggers when the drag is fiished
  • Dropping Event

  • dragenter: Triggers when the drag enters a drop zone
  • dragover: Triggers continuously as the element is dragged over the drop zone
  • dragleave: Triggers when the dragged item leaves a drop zone
  • drop: Triggers when the dragged item is dropped

Code Example:

<script>
    var $draggedItem;
    $(function() {
        $(".item").on("dragstart", Dragging);
        $(".item").on("dragend", DraggingEnd);
        $(".hole").on("dragenter", PreventDefault);
        $(".hole").on("dragover", PreventDefault);
        $(".hole").on("drop", DropItem);
    });
    function Dragging(e) {
        $(e.target).addClass("dragging");
        $draggedItem = $(e.target);
    }
    
    function DraggingEnd(e) {
        $(e.target).removeClass("dragging");
    }
    function PreventDefault(e) {
        e.preventDefault();
    }
    
    function DropItem(e) {
        var hole = $(e.target);
        if (hole.hasClass("hole") && hole.children().length == 0) {
            $draggedItem.detach();
            $draggedItem.appendTo($(e.target));
        }
    }
</script>
            
  • DataTransfer Object

  • The previous example demostrates a drag and drop, but you can also use the DataTransfer object to pass data from the dragstart event to the drop event.

Code Example:

                    some code here