HTML Drag and Drop

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

HTML Drag and Drop

HTML Drag and Drop

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept that is used to copy, reorder and delete items with the help of a mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

If you want to achieve the Drag and Drop functionality in traditional HTML4, you must either have to use complex JavaScript programming or other JavaScript frameworks like jQuery, etc.

Events for Drag and Drop feature

Event Description
Drag It fires every time when the mouse is moved while the object is being dragged.
Dragstart It is a very initial stage. It fires when the user starts dragging an object.
Dragenter It fires when the user moves his/her mouse cursor over the target element.
Dragover This event is fired when the mouse moves over an element.
Dragleave This event is fired when the mouse leaves an element.
Drop Drop It fires at the end of the drag operation.
Dragend It fires when the user releases the mouse button to complete the drag operation.

HTML5 Drag and Drop Example

Let's see an example of the HTML 5 drag and drop feature.

To understand this example, you must have knowledge of JavaScript.

<script>  

function allowDrop(ev) {ev.preventDefault();}  

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

function drop(ev) {  

ev.preventDefault();  

var data = ev.dataTransfer.getData("text/html");  

ev.target.appendChild(document.getElementById(data));  

}  

</script>  

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

<div id="div1" style="width:350px;height:100px;padding:10px;border:1px solid #aaaaaa;"   

ondrop="drop(event)" ondragover="allowDrop(event)"></div>  

<br>  

<img id="drag1" src="/htmlpages/images/javatpoint.png" alt="javatpoint image"   

draggable="true" ondragstart="drag(event)"/>  

In the above example, we have used ondrop and ondragover events on div element, and ondragstart event on img tag.

Output:

Drag the samtpoint image into the rectangle:

 


 


Note: MouseEvent is not fired during the drag operation.

 

Stages during Drag and Drop operations

1) Make an element draggable

If you want to make an element draggable, set the draggable attribute to "true" on the element. For example:

 

<img draggable = "true">   

2) What to drag:

Use ondragstart and setData () methods.

Specify what should happen when the element is dragged.

3) Where to Drop:

Use ondragover event.

4) Do the Drop:

Use ondrop event.