HTML5 Drag and Drop Demo

I've done some research about HTML5 APIs, today I want to show you the Drag and Drop.

It's pretty cool and best of all works in all major browsers!

So I've built a simple demo playing with containers and HTML data attributes. We'll retrieve the containers attributes once we drop them in the drop zone.

Costs App Calculator

Let's get into it.


Fairly simple HTML, all you need is the drop zone and the draggable items:

<div id="drop"></div> <div draggable="true" class="dragable-item" data-title="Box 1" data-price="200">1</div>
Code language: HTML, XML (xml)

The JavaScript

Here comes the juicy part. Basically what we want to do is add event listeners to the draggable items and to the drop zone.

We'll use callback functions to create actions when the items are dropped inside the drop zone.

I'm using jQuery just as a selector and for DOM manipulation. You could use pure JavaScript or an other library of your choice, it's not required for the code to work.

// Callback function when cancelling the event function cancel(e) { if (e.preventDefault) { e.preventDefault(); } return false; } // Get the #drop zone var drop = document.getElementById('drop'); var draggedItem = null; // Add the Event Listener to each draggable item $('.dragable-item').each(function(index){ $(this)[0].addEventListener('dragstart',function(e){ draggedItem = jQuery(this); e.dataTransfer.setData('Text',; // required otherwise doesn't work },false); }); drop.addEventListener('dragover', cancel); drop.addEventListener('dragenter', cancel); drop.addEventListener('drop', function (e) { // Prevent default browser behaviour e.preventDefault(); // Here you can do anything you want return false; });
Code language: JavaScript (javascript)

What I've done with the demo is retrieve the data attributes and print them inside the drop zone (check the Demo page source code for full details)

What about mobile?

HTML5 got you covered! There are touch events ready to boost your code on mobile devices.

Check out the full list on HTML5 Rocks.

Unfortunately I haven't been able to completely adapt this demo for touch devices, I'll update as soon as I can.


View Demo

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast


Leave a Reply

Add <code> Some Code </code> if you need to.