/    /  HTML Drag & Drop

HTML Drag & Drop

 

The HTML5 drag and drop feature specifies the user to drag and drop an element to another location. The drop location may be a different application. While dragging an element(image) a translucent representation of the element is to follow by the mouse pointer.

 

Drag and Drop Events:

 

Drag –  It fires each 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 objects.

Dragenter – It fires when the user moves his or her mouse cursor over the target element.

Dragover – This event is fired when the mouse moves over an element.

Dragleave – It is fired when the mouse leaves an element.

Drop – It fires at the end of the HTML drag operation.

Dragend – It fires when the user releases the mouse button to complete the HTML drag operation.

 

Example:

 

HTML 5 drag and drop feature.

 

<!DOCTYPE html> 
<html>
<body>

<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="https://pbs.twimg.com/profile_images/940799311503294465/X3oqt2UF.jpg" alt="i2 tutorials "   style="width:100px";
draggable="true" ondragstart="drag(event)"/> 

</body> 
</html>

 

 OUTPUT:

 

HTML Drag & Drop

 

HTML Drag & Drop

 

We have used on-drop and ondragover events on the div element, and ondragstart event on the image(img) tag

 

During Drag and Drop operations:

 

1. Make an element draggable:

 

The element was draggable, set the draggable attribute to “true” on the element.

<img draggable = “true”>

 

2. What to drag:

 

Use ondragstart and setData () methods. Provide what should happen when the element is dragged.

 

3. Where to Drop:

 

Use ondragover event.

 

4. Do the Drop:

 

Use ondrop event.

 

Supporting Browsers:

 

HTML Drag & Drop