Wednesday 2 October 2013

Drag and Drop in a webpage

I saw a cool feature on a website allowing you to drag and drop a file onto the page and it will be uploaded.

I wondered how this was done and after some experimentation I believe I understand how to do this. I should note that I was working with firefox on Linux and I have not tested this code in other browsers on other platforms.

I created a simple blank html page with a line explaining to drag and drop a file onto the page.

Then a little javascript to handle the dragging and dropping a file.

In my script I need to get the whole document (or the body element) which can be done with
document.documentElement

Then I need to add some event listeners to this to listen for the drag and drop events (in particular the "drop" event). I created some functions to be called when these events are triggered.
To prove a file has been dropped all I did was popup an alert with the name of the file dragged and dropped.
My test code only handled the first file dropped, but it should not be too difficult to add a loop to process the rest.

So my basic javascript would look like this
function noop(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
}

var drop = document.documentElement;

drop.addEventListener("dragover", noop, false);
drop.addEventListener("dragexit", noop, false);
drop.addEventListener("drop", function(e) {
     e.stopPropagation();
     e.preventDefault();
     //only get the first file, add loop for multiple file handling
     var files = e.dataTransfer.files;
     var file = files[0];
     alert("file '"+file.name+"' dragged and dropped");
     return false;
},false);

This was not successful and kept giving me an error in firefox, this was probably due to trying to do things before the document was ready. Therefore I used jQuery to ensure the document was ready, now my code was wrapped like so

$(document).ready(function() {
...
});

However, this still did not seem to be working. I found some old bugs which suggested that firefox had problems with drag and drop from anything other than nautilus, but I was using nautilus so it should work.
Then it struck me I was dragging items from the recent files window in nautilus, could these be references to the files? I opened the actual directory where the test files were and drag and drop worked perfectly.

I did not do anything with the file dropped, but is should not be difficult to add upload code to pass to a server side script for processing.