Drag Drop Sample with HTML5

Feb 20 2014

Drag Drop is a very common feature. HTML5 introduced it as a stranded feature. Any element can be dragged into HTML5.

Following is a very simple example of drag-drop feature. There are four images that could be dragged from div1 to div2.




<style type="text/css">

#div1 {width:550px;height:70px;padding:10px;border:1px solid #aaaaaa;}

#div2 {width:550px;height:70px;padding:10px;border:1px solid #aaaaaa;}


<script type="text/javascript">

function allowDrop(evt)




function drag(evt)




function drop(evt)


var data=evt.dataTransfer.getData(“Text”);







<p>Simple drag drop sample:</p>

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

<br />

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

<img id="drag1" src="images/image.png" draggable="true" ondragstart="drag(event)" />

<img id="drag2" src="images/image.jpg" draggable="true" ondragstart="drag(event)" />

<img id="drag3" src="images/image.png" draggable="true" ondragstart="drag(event)" />

<img id="drag4" src="images/image.png" draggable="true" ondragstart="drag(event)" />




To make an element draggable, set the draggable attribute to true.

"<img draggable=true >"

Then specify what should happened when the element is dragged.

In above example we are calling drag function “ondragstart” event. The datatransfer.setData methods sets the data type and the value of dragged data.

The ondragover event specifies where the dragged data can be dropped. By default data can’t be dropped on other element. To allow a drop, We must prevent the default handling of the element. We used event.preventDafault method for it.

Now final step is what should happen when an element dropped. In above example we are appending element into target element. We can also set the value of an input field if require.

I hope this example helps you to understand the drag-drop feature of HTML5.