HTML5 - Drag and Drop Tag




HTML5 Drag and Drop Tag

HTML Drag and Drop interfaces enable applications to use drag and drop features in Google Crome, Safri, Firefox and other browsers. For example, with these features, the user can select draggable elements with a mouse, drag the elements to a droppable element, and drop those elements by releasing the mouse button.

Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it much easier to code up.

Drag And Drop Events

At every stage of the drag and drop operation a different event is fired so that the browser knows what JavaScript code to execute; the events are −

dragStart − fires when the user starts dragging the element.

dragOver − fires when the mouse is moved over an element when the drag is occurring.

drag − fires every time we move the mouse during the dragging of our element.

dragEnd − fires when the user releases the mouse while dragging the object.

dragEnter − fires when the draggable element is first dragged over the target element.

dragLeave − fired if the user’s cursor leaves an element when dragging.

drop − fired when the actual drop is performed.

Example

<!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 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>
<img src="img/nechar1.jpg" alt="Nechar1" style="width:100%">
</body>
</html>

Result

Drag the image into the rectangle:


Nechar1