Implementing Drag and Drop Functions with HTML5 and JavaScript

With HTML5 and JavaScript, you can implement native drag and drop functions within the Web browser.

This is one of the emerging HTML5 tools that promises to make websites more interactive without relying on additional technologies such as Flash. In this tutorial we will create a simple page with images the user can drag and drop into designated areas.

Create an HTML5 Web Page

Create an HTML file for your drag and drop function. Use the following basic outline, with sections for JavaScript and CSS in the head area:

Add Drag Targets to the Page

Your page will contain elements that can be dragged and elements in which the dragged items can be dropped. Start with the areas your user will be able to drop draggable elements into, adding the following in your page body section:

The draggable images in the page will be able to drop within these elements. Each has an ID to identify it within the JavaScript code. The “ondrop” event specifies a function that will execute when an item is dropped over one of these elements. The “ondragover” event simply instructs the browser not to do what it does by default, which is to prevent items being dropped within other elements – we are telling the browser to allow elements to be dropped by preventing this default behavior.

Add Draggable Elements to the Page

Let’s use a couple of image elements to drag within the page. Use the following markup for each one, altering the image source attributes for your own images:

Alter the width and height to suit your own images and give each one a unique ID attribute value. The draggable attribute instructs the browser to allow users to drag the image element. The “ondragstart” event attribute specifies a JavaScript function to execute when dragging commences. Add a couple of these inside two of your placeholder elements, resulting in markup like this:

These declarations apply to all elements whose ID attributes begin with “place” as our holder elements do. The shorthand notation uses a wildcard to specify this, rather than having to specify every ID attribute for the elements that your items can be dropped within. Alter the dimensions to suit your images and the styling for backgrounds or borders in any way you like. To make the demonstration clearer, you can add the following HTML at the bottom of the page:

If you look at your image elements you will see that this is the function specified within the “ondragstart” event attribute. The content of the function specifies the image element, letting the browser know that is what to drag. The function receives an event variable providing access to data about the element being dragged.

Implement Dropping

Add the following function after your dragging function:

//function called when element drops
function dropIt(theEvent) {
//get a reference to the element being dragged
var theData = theEvent.dataTransfer.getData("Text");
//get the element
var theDraggedElement = document.getElementById(theData);
//add it to the drop element
theEvent.target.appendChild(theDraggedElement);
//instruct the browser to allow the drop
theEvent.preventDefault();
}

This code first gets a reference to the dragged element, then adds it to the element it is being dropped in. Again, the code tells the browser not to implement the default behavior so that the image can be dropped successfully. This function also receives the event data indicating information about the dragged element and the element being dropped over.

Open your page in the browser and test it by clicking and dragging the images. Notice that if you drag the images over a page area that you have not explicitly instructed the browser to allow dropping in, they snap back to their original position. As long as you drop over a designated element, your images can be moved around. Notice also that if you drop one image on top of another, the next time you drag one, they both drag.

Conclusion

HTML5 functions bring a greatly enhanced level of interactivity to Web development. The future looks pretty exciting, but for the moment remember to take care of users with browsers that do not support these emerging techniques.

Sue Smith works as a Web/ software developer and technical writer based in the UK: see benormal.info for details. Sue has written for various clients including Smashing Magazine and Mobiletuts+. She also does a little Android development and some comedy writing.
More articles by Sue Smith

Bart De Kimpe

Any chance of a demo page?

Romain

I think you should consider keeping the JS stuffs in js part and not in the div / img tags as you did in the second part, using event listeners set on window.onload event :

It may be just me, but I feel that the image being dragged should replace the image in the drag-to area.

Rick

I agree. Did you ever figure out a fix for this?

samuel

good, but the image dragged on an other make the first one disappear.. i managed to fix this, but have any idea how i could check where are the image (in which dropbox) ?
thks !

Rick

How did you fix the image from disappearing?

Aleksandar Malenko

Can you please tell me how did you fix this ?

Aleksandar Malenko

how did you fix it?

Monty

Awesome!

Ashwani

can i use your information in my blog.with back link to your website

JimTEFL

This is very good but nowhere in any of these website examples can I find out how to do what I call a controlled drag and drop. Take a chequers board with its 32 playing squares, sq#1 being at the top left. If a king were on sq#6 it can move onto sq#2, sq#3, sq#10 and sq#11. If I could identify the source sq# (not the king) and compare it with the target sq# I could allow drops on the above quoted sqs, the comparisons having given me 4(6-2), 3(6-3), -4(6-10) and -5(6-11).
I have a beautiful board and can move pieces onto targets but not with the above move limitations.
I welcome an effective solution here, please.

Hey WordPress lovers. Every month dozens of incredible free WordPress plugins are released by the community, and we’re here to bring them to you. This seems to be a month of small but useful utilities that only do one or two things, with a few exceptions. So go on. March on down to the list, and get to it! (I'm only a little bit ashamed of that pun.) WP NoteUp ... Notes! Alongside your posts and pages! Use them to remind yourself, or other authors, about things you'd put in a note. That's really all there is to...

WordPress plugins are coming out all of the time, right and left. Every day, they’ve got new ones in the WordPress plugin repository for the curious developer to check out. Over time, your average designer or developer will end up with a list of their favorites. Usually, they’re plugins that solve common problems, are up-to-date and well-maintained, with good support. With that in mind, we’re sharing a list of some of the best plugins out there. Disable Comments ... Disable Comments does......

When I first started out creating websites with WordPress, I was in awe of the depth and variety of plugins available. During those golden days I would willingly install just about anything that looked cool. Shortly thereafter, I was smacked in the head by reality. Stuff started breaking and seriously hurt my good time. It turns out that not every plugin is a great one. And there are times when it seems like the work we do is held together with bubble gum and duct tape. Everything works splendidly until it...

WordPress is undoubtedly one of the most popular tools on the Internet because it makes it so easy to get a functional web site up and running in such a short time. And then there are the plugins. If you want your WordPress site to do something then odds are there is a plugin that you can install to make your site do what you want it to do. But plugins pose a bit of a problem at times. Since they are created by third-party developers you never know what quality control practices are used and what security testing...

WordPress beginners have difficulty customizing their websites past simple text changes, especially if they have no background knowledge of HTML or CSS. WordPress page builder plugins allow just about anyone to build a stylish or professional looking web page, through a user-friendly interface - quickly, and without knowing HTML or CSS. Though it may seem like WordPress page builder plugins have usefulness mainly for the technically unsavvy, they can also make a WordPress developer’s job...

Oftentimes, setting up a WordPress website results in a haphazard scramble to configure enough of the right plugins to make the client happy, and address any specific needs they might have mentioned. But a failure to install certain plugins means the client will come back at you with questions as to why it wasn’t done in the first place. Though you’re probably happy to rectify the problem (and collect a little extra money on the project), going back in to install plugins can distract from more profitable...

In Part 1 of this series we took a look at how you can better secure your WordPress files during, and after, the installation of the software. But once you have the files hardened against different threats, it is time to start looking at some of the different plug-ins available that can help you further protect and secure your WordPress site. WordPress Firewall 2 ... Having worked with a company that deals with web application firewalls, I can tell you from firsthand experience that these are by far one...

There’s a goal behind every website, and a specific chain of events that must occur before each goal is accomplished. Whether you want someone to sign up for your email newsletter, or fill out a contact form, these things don’t happen without the proper triggers. Used strategically, WordPress plugins can assist with the realization of important goals. Here’s how to turn your website into a conversion machine with WordPress Plugins. Essential Grid ... Essential Grid is an all-around grid solution...

About

DeveloperDrive.com is a blog about web development from the makers of the popular web design blog WebdesignerDepot.com
Founded in 2011, we focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.