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. <!DOCTYPE HTML> <html> <head> <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;} </style&gt <script type="text/javascript"> function allowDrop(evt) { evt.preventDefault();   function drag(evt) { evt.dataTransfer.setData(“Text”,evt.target.id); } function drop(evt) { var data=evt.dataTransfer.getData(“Text”); evt.target.appendChild(document.getElementById(data)); evt.preventDefault(); } </script> </head> <body> <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)" /> </div> </body> </html> 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.