Example to implement HTML5 drag and drop with list of Events

Example to implement html5 drag and drop with list of Events

You must remember during the age of HTML4 to implement drag and drop feature generally we do Scripting. This problem is addressed in HTML5. Using HTML5 you don’t need to depend upon Scripts. There are per-defined APIs using which we can easily implement HTML5 Drag and Drop feature. Drag and Drop makes life easier. It saves user Time. Operations like Copy, Reorder & Deletion can be more user friendly using Drag and Drop.

Let’s discuss about the scenario where I have 2 divs. In first div there is an image which I want to drag into the 2nd div. Here my 2nd div acts like a container. Look at the example in below:

Example of HTML5 Drag and Drop

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Example of HTML5 Drag n Drop</title>
<style type="text/css">
border: 1px solid #aaaaaa;
height: 152px;
padding: 10px;
margin-right: 10px;
width: 150px;
<script type="text/javascript">
function allowDrop(ev) {

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

function dropImage(ev) {
var data = ev.dataTransfer.getData("text");
<div class="container" ondrop="dropImg(event)" ondragover="allowDrop(event)"></div>
<div class="container">
<img id="dragimg" draggable="true" src="drag-pattern.png" ondragstart="dragImage(event)">

HTML5 Drag and Drop Events

HTML5 Drag and Drop API provides the following events.

  • dragstart: This event occurs when the user starts dragging the object. Generally we use this event to show errors. I mean if an user dragging object into an area where drop facility is not available using dragstart we can show the error message.
  • dragenter: Using mouse while you are dragging an object during that time this event occurs.
  • dragover: This event occurs as the mouse is moved over an element during dragging.
  • dragleave: This event occurs when the mouse leaves an element during dragging.
  • drag: This event occurs every time the mouse is moved during the object is being dragged.
  • drop: This event occurs at the end of the drag operation.
  • dragend: This event occurs when the user releases the mouse button during dragging.

HTML5 Drag and Drop feature was supported by all the major browsers like Google Chrome 4.0, Mozilla FireFox 3.5, Safari 6.0, Internet Explorer 9.0, Opera 12 & above versions.