Home arrow HTML arrow Page 2 - Drag and Drop API in HTML5
HTML

Drag and Drop API in HTML5


In this first part of a two-part tutorial, I will show you how to use the Drag & Drop API included with HTML5. As you'll see, dragging and dropping files from your local hard drive to a predefined section in the target HTML document is quite a simple process, whose workhorses are the “dragover” and “drop” event handlers.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
October 03, 2011
TABLE OF CONTENTS:
  1. · Drag and Drop API in HTML5
  2. · Dragging and dropping local files into the previous web page

print this article
SEARCH DEVARTICLES

Drag and Drop API in HTML5 - Dragging and dropping local files into the previous web page
(Page 2 of 2 )


 
In reality, dragging and dropping files into the earlier web page is a pretty straightforward process that can be tackled with only minor hassles. To achieve this, the Drag & Drop API provides two primary event handlers (aside from a few additional ones) called “dragover” and “drop,” which makes the process a no-brainer.

But it’s time to stop talking and show the JavaScript snippet that brings the API to life. Here it is:

// attach the event handlers and handle the dropped files
function handleFiles() {
    // get the file container
    var filecont = document.getElementById('file-container');
    if (filecont === null) {
        return false;
    }   
   
    // attach the 'dragover' event to the file container
    filecont.addEventListener('dragover', function(event) {
        event.preventDefault();
    }, true);
   
    // attach the 'drop' event to the file container
    filecont.addEventListener('drop', function(event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        filecont.innerHTML = '<h2>You have dropped ' + files.length + ' files.</h2>';
    }, true);    
}

That looks quite easy to grasp, right? As the above code bit shows, I defined a simple function called “handleFiles()” which attaches the aforementioned event handlers to the droppable container. It also prevents the browser from following its default behavior, that is to display (when possible, of course) the dropped files in a separate window.

While it’s fair to admit that the way that the events are handled is pretty intuitive, you should pay close attention to the function’ segment responsible for retrieving the local files. Yes, the following line:

var files = event.dataTransfer.files;

effectively gets the dropped files via a new JavaScript object called “dataTransfer” and stores them as a file list in a local variable (pretty similar to what you do with a regular DOM collection). Lastly, the number of files that have been dropped into the target container is displayed by using the familiar “length” property.

Additionally, it’s necessary to call the previous function after the web page finishes loading, which is handled by the fragment below: 

// call the 'handleFiles()' function after the web page has been loaded
window.addEventListener('load', handleFiles, true);

All in all, at this stage you should have a clearer idea of to get things rolling with the Drag & Drop API. Even so, if you’re anything like me, you’ll want to see if the previous function can be used for dragging and dropping local files to the specified container. Well, to prove this, in the following section I’ll be attaching the function to the web page defined before, so you can give it a try using Firefox.  

Now, leap forward and read the lines to come.

The example’s full source code

As I promised in the preceding segment, below is the full source code corresponding to the previous web page, including the JavaScript function that puts the Drag & Drop API into action. Check it out: 

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML 5 Drag'n Drop API</title>
<script>
// attach the event handlers and handle the dropped files
function handleFiles() {
    // get the file container
    var filecont = document.getElementById('file-container');
    if (filecont === null) {
        return false;
    }   
   
    // attach the 'dragover' event to the file container
    filecont.addEventListener('dragover', function(event) {
        event.preventDefault();
    }, true);
   
    // attach the 'drop' event to the file container
    filecont.addEventListener('drop', function(event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        filecont.innerHTML = '<h2>You have dropped ' + files.length + ' files.</h2>';
    }, true);    
}

// call the 'handleFiles()' function after the web page has been loaded
window.addEventListener('load', handleFiles, true);
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h1 {
    font-size: 5em;
    color: #585858; 
}
h2 {
    font-size: 4em;
    text-align: center;
    color: rgba(192, 192, 192, 0.7);
    text-shadow: 1px 1px 0 #FFF;
}
/* main wrapper */
#wrapper {
    width: 780px;
    margin: 0 auto;
}
/* file container */
#file-container {
    width: 300px;
    min-height: 300px;
    margin: 0 auto;
    background: #eee;
    border: 3px dotted #585858;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>HTML 5 Drag'n Drop API</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </header>
        <section>
            <div id="file-container">
                <h2>Drop your files right here...</h2>
            </div>
        </section>
        <footer>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </footer>
    </div>
</body>
</html>
 
That was the boring part. So, it’s time to have some fun! Simply browse to a local folder on your machine and open it up, as shown in the snapshot below:

Now, drag any file residing in the folder and drop it into the target area of the earlier web page (you can select multiple files, too). If all goes well, the area should display a message similar to this one: 

That worked like a charm, indeed. Effectively, thanks to the functionality offered by the Drag & Drop API, it’s really easy to drag and drop local files to a selected area on an HTML document. But hang on a second! While showing the number of files dropped into the pertinent area is all well and good, the process, per se, is not very useful.

Don’t feel concerned, though, as in the final chapter of this tutorial I’ll be showing how to parse the dropped files and show their contents in the web page’s target area. 

Closing remarks
  
In this introductory part of this two-part tutorial, I went through the development of a basic example, which showed how to use the Drag & Drop API included with HTML5. As you just saw, dragging and dropping files from your local hard drive to a predefined section in the target HTML document is quite a simple process, whose workhorses are the “dragover” and “drop” event handlers.

So far, I've taught you how to employ the API in a pretty basic and somewhat limited way. But, as I said before, things are about to change, as in the forthcoming installment I’ll be extending the earlier example by providing it with the ability to parse the dropped files and display them (as long as they’re image files) on the target area. Obviously, all of these tasks will be performed through the counterpart of the Drag & Drop API -- that is, the File API mentioned at the start.

So, stick with my usual recommendation, and don’t miss the final part!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials