HTML Drag & Drop

Drag and Drop (DnD) is powerful User Interface concept which allows the user to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.

It is very useful to copy, reorder and deletion of items with the help of mouse clicks.

Drag & Drop Events

Event Description
dragstart It fires when the user starts dragging of the object.
dragenter It fired when the mouse is first moved over the target element while a drag is occurring. A listener for this event should indicate whether a drop is allowed over this location.
dragover This event is fired as the mouse is moved over an element when a drag is occurring. Much of the time, the operation that occurs during a listener will be the same as the dragenter event.
dragleave This event is fired when the mouse leaves an element while a drag is occurring. Listeners should remove any highlighting or insertion markers used for drop feedback.
drag It fires every time the mouse is moved while the object is being dragged.
drop The drop event is fired on the element where the drop was occurred at the end of the drag operation. A listener would be responsible for retrieving the data being dragged and inserting it at the drop location.
dragend It fires when the user releases the mouse button while dragging an object.

Drag & Drop Example

Below example will demonstrate the basic architecture of HTML Headings.

<!DOCTYPE HTML>
<html>
    <head>
        <style>
            #div1 {
              width: 350px;
              height: 70px;
              padding: 10px;
              border: 1px solid #aaaaaa;
            }
        </style>

        <script>
            function allowDrop(ev) {
              ev.preventDefault();
            }

            function drag(ev) {
              ev.dataTransfer.setData("text", ev.target.id);
            }

            function drop(ev) {
              ev.preventDefault();
              var data = ev.dataTransfer.getData("text");
              ev.target.appendChild(document.getElementById(data));
            }
        </script>
    </head>
    
    <body>

        <p>Drag the W3Schools image into the rectangle:</p>

        <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
        <br>
        <img id="drag1" src="../images/html/logo.png" draggable="true" ondragstart="drag(event)" width="336" height="69">

    </body>

</html>