In a previous post, we showed you how to upload several files using the input
element. In Firefox 3.6, you can let your users drag and drop files directly into your web page, without going through the file picker.
Demo
If you’re running the latest Firefox 3.6 beta, check out our interactive demo of drag and drop. It showcases two technologies: the Drag and Drop API and the File API.
Drag and Drop Events
To use drag and drop, you first need to tell the browser that a given element can handle dropped objects and will respond to a drop action, using the dragover
and drop
events.
You also need to prevent the browser’s default behavior, which is to simply load the dropped object in the browser window.
dropzone.addEventListener("dragover", function(event) {
event.preventDefault();
}, true);
dropzone.addEventListener("drop", function(event) {
event.preventDefault();
// Ready to do something with the dropped object
}, true);
You may also want to use the dragenter
and dragleave
events to be notified when a drag session starts or stops.
Your element is now ready to receive files with the drop
event.
Manipulating the Files
On the drop
event, you can access the files with the files
property of the DataTransfer object:
dropzone.addEventListener("drop", function(event) {
event.preventDefault();
// Ready to do something with the dropped object
var allTheFiles = event.dataTransfer.files;
alert("You've just dropped " + allTheFiles.length + " files");
}, true);
Once you’ve accessed the files, the File API lets you do much more, like parsing files as a binary array, or displaying a preview of an image by reading the file as a DataURL.
Of course, you can still drag and drop data other than files (e.g. text, URLs, remote images …) using the drag and drop API.
About Paul Rouget
Paul is a Firefox developer.
32 comments