Drag and Drop IN HTML5

Introduction

 
In this article, I describe the "Drag and Drop (DnD)" feature of HTML5. We will define in this article a draggable image that can be dropped into a rectangle.
 

Drag and Drop

 
Drag and Drop is a very common feature supported by HTML5. By doing this you can grab an object and drag it to a different position of your page. Making an object draggable is simple. Set the "draggable= true" attribute on the element you want to make moveable. You can drag anything you want.
Procedure to drag the image
 
Step 1
 
To make the element draggable, set the draggable attribute to true. 
 
<img draggable="true">
 
Step 2
 
Now we specify what will happen when the element is dragged. The datatransfer property is where all the DnD magic happens. It holds a piece of data sent in the drag action.
 
The ondragstart attribute calls a function, "drag(event)" that specifies what data to be dragged. The "dataTransfer.setData()" method set the data type and the value of the dragged data.
 
Step 3 
 
The ondragover event specifies where the dragged data can be dropped. By default, the element (data) cannot be dropped in another element. To allow the drop you must prevent the default handling of the event. In case you are dragging something like a link, you need to prevent the browser default behavior in order to navigate to the link.
 
Step 4
 
When the data that is dragged is dropped, the drop event occurs.
 
Browser Support
 
The Drag and Drop feature is supported by Internet Explorer 9, Firefox, Opera 12, Chrome and Safari 5.
 
This feature is not supported by Safari 5.1.2.
 
Coding of Drag and Drop in HTML5
  1. <!DOCTYPE HTML>  
  2. <html>  
  3.    <head>  
  4.       <style type="text/css">  
  5.          #div1  
  6.          {  
  7.          width:400px;  
  8.          height:350px;  
  9.          padding:10px;  
  10.          border:1px solid blue;  
  11.          }  
  12.       </style>  
  13.       <script>  
  14.          function allowDrop(e) {  
  15.              e.preventDefault();  
  16.          }  
  17.          function drag(e) {  
  18.              e.dataTransfer.setData("text", e.target.id);  
  19.          }  
  20.          function drop(e) {           
  21.              e.preventDefault();           
  22.              var data = e.dataTransfer.getData("text");           
  23.              e.target.appendChild(document.getElementById(data));          
  24.          }  
  25.       </script>  
  26.    </head>  
  27.    <body>  
  28.       <p>Drag the image into the rectangle:</p>  
  29.       <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>  
  30.       <br>  
  31.       <img id="drag1" src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" draggable="true" ondragstart="drag(event)" width="350" height="300">  
  32.    </body>  
  33. </html> 
Output
 
Before Drag and Drop
 
drag.jpg
 
After Drag and Drop
 
Drop.jpg