HTML5 and file Drag & Drop
Thursday 13 October 2011
Of course as always not every browser supports the new feature. According to CanIUse.com 88.92% of browser support Drag&Drop, including Internet Explorer 6 and above, but it turns out this is a little optimistic as IE 9 does support Drag & Drop but not with files. This works just fine with the current versions of Chrome or FireFox though.
The HTML page I am using is real simple and looks like this.
A few things to note. I am using a <div> with an ID of dropTarget to drop the files from the explorer and there is an <ul> with ID images where the result of the drop is going to be shown.
Also I am using jQuery but the jQueryUI droppable function doesn’t support dragging and dropping files from the explorer at this time.
To work with file drops we need to handle 2 events, the dragover and the drop, by adding event handlers using the native addEventListener() function.
The dragover event is real simple, all we need to do is prevent the browser from doing it’s default behavior.
The drop event is more interesting. First of all we need to check the passed argument to see if the is a files array on the dataTransfer object. In the case of Internet Explorer 9 this is not the case. Next we can use the $.each() function as a convenient way of handling the file drops. In this case all I am doing is showing the file name in the list.
Sweet, now it would be nice if IE also supported this API.