HTML5

HTML5 Drag and Drop Example

Photo of Viraj KhatavkarViraj KhatavkarDecember 1st, 2014Last Updated: June 20th, 2018
4 1,374 3 minutes read

Usability, an important part of web interface eases the way we communicate with web. Many new technologies and functionalities are invented to ease the development effort as well as improve the overall way in which users interact with web. HTML5 has given many things as of today to improve the browser functionalities on client side with minimum amount of scripting. It provides a great way to implement drag and drop functionality in modern browsers. We are going to see how it is implemented with a basic example of drag and drop in an image from one div to another.

Want to be anHTML5 Ninja?
Subscribe to our newsletter and download the HTML5 Programming Cookbookright now!
In order to get you prepared for your HTML5 development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

To achieve drag and drop functionality with traditional HTML4, developers would have to use complex Javascript code. HTML 5 provides a Drag and Drop API that brings support to the browser making it much easier to code up. No extra plugins needed to be installed. It is supported by the following major browsers:

  1. Internet Explorer 9+
  2. Firefox
  3. Opera, Chrome
  4. Safari

Note: Drag and drop does not work in Safari 5.1.7 and earlier versions.

1. Setting up two divs

We will first code two create two div boxes. One div will contain the image to be dragged. The other div will be the destination where the image needs to be dragged.

<!DOCTYPE html><html><head>    <style>        #div1, #div2        {float:left; width:280px; height:180px; margin:10px;padding:10px;border:1px solid #aaaaaa;}    </style></head><body><div id="div1"> <img src="drag.png" width="250" height="150" id="drag1"></div><div id="div2"></div></body></html>

Output for above code is two div boxes with one div box containing our image

1 drag and drop
Initial divs

2. Make the elements draggable

Now, we need to first make the image draggable. Set the attribute"draggable = true"

<div id="div1"><img src="drag.png" draggable="true" width="250" height="150" id="drag1"></div>

3. Set up events to handle drag functionality

Set theondragstart event in theimg tag to calldragInitiliaze() function as follows :

<img src="drag.png" draggable="true" ondragstart="return dragInitialize(event)" width="250" height="150" id="drag1">

Theondragstart event inimg tag detects when the drag is initialized and then it calls thedragInitiate() function. ThedragInitiate() function, then catches the event. It sets theeffectAllowed value to “move” and has dataTransfer.setData() method which sets the data type and the value of the dragged data.

<script type="text/javascript">function dragInitialize(ev) {ev.dataTransfer.effectAllowed='move';ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));return true;}</script><!-- In body add the following draggable attributes to first div --><div id="div1" ><img src="drag.png" draggable="true" ondragstart="return dragInitialize(event)" width="250" height="150" id="drag1"></div>
2 drag and drop
Dragging Image from one div to other

4. Completing the drop and putting it all together

By default, the elements that are set to bedraggable cannot be dropped in any other elements. The drop functionality needs to be handled by events provided by Drag-and-Drop API. We have to take care of following things :

function allowDropStatus(ev) {ev.preventDefault();return false;}function dropComplete(ev) {ev.preventDefault();var src = ev.dataTransfer.getData("Text");ev.target.appendChild(document.getElementById(src));ev.stopPropagation();return false;}<!-- Modify the 2nd div to accept the drop --><div id="div2" ondrop="return dropComplete(event)" ondragover="return allowDropStatus(event)"></div>
  1.  The div should listen to drop event so that it can accept the drop and place the image in its destination.
  2. ondragover listener event is fired whenever a dragged image is over the destination div
  3. allowDropStatus() prevents the default browser action so that we can code and handle the drop functionality.
  4. dropComplete() function does following three tasks :
  • Prevents default browser action after the image has been dropped
  • Fetches the data of image fromgetData which was stored while the image was selected for drag
  • Appends the data to new div
  • Stops the propagation of image

If you observe carefully, we can drag the image from first div to second. But, what if we want to drag the image back to first div. The image is set todraggable, so it will be dragged. But, our first div is not set to handle drop. Let’s modify our first div so that it can handle the drop.

We put following two listeners in first div to accept drop :

  1. ondragover listener which calls allowDropStatus function
  2. ondrop  listener which calls dropComplete function
<div id="div1" ondrop="return dropComplete(event)" ondragover="return allowDropStatus(event)"><img src="drag.png" draggable="true" ondragstart="return dragInitialize(event)" width="250" height="150" id="drag1"></div>
3 drag and drop
Completing drop in second div


This completes our simple example for Drag and Drop. It is totally based on handling of events and listeners which are provided by native HTML5 API

Conclusion and further applications

So, now we can drag  images back and forth efficiently. Drag and Drop functionality has numerous uses in improving the overall usability. Using the logic presented above and a glimpse of how various events of Drag-and-Drop API can be used, you can extend them to use and apply for any other functionality. As with any technology, HTML 5 Drag-and-Drop API has its own advantages and disadvantages. Its upto you too whether use it or not.

Download
You can download the full source code of this example here :HTML 5 Drag and Drop
Do you want to know how to develop your skillset to become aWeb Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Viraj KhatavkarViraj KhatavkarDecember 1st, 2014Last Updated: June 20th, 2018
4 1,374 3 minutes read
Photo of Viraj Khatavkar

Viraj Khatavkar

Viraj has graduated from University of Mumbai, the financial heart of INDIA. Being a web geek & having entrepreneurship in DNA; happens to be the Co-Founder of Tantra-Gyan (I) Business Solutions, heading Technology space. He loves PHP to the core and is great enthusiast for mastering the same. He prefers designing architectural planning of an application and researching new architectural solutions. He has developed various solutions logical as well as architectural for service industry web ERPs and Scraping apps. He is fascinated about SOA, web services and believes "Good design increases software life and your leisure time as well :)" Loves spending time for creating solutions for the betterment of society namely focusing on Education, Employment & Civic Rights. Buzz him any moment, if you feel like; he would love to hear from you.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.