Prevent browser from loading a drag-and-dropped file

Travis picture Travis · Jul 20, 2011 · Viewed 75.1k times · Source

I'm adding an html5 drag and drop uploader to my page.

When a file is dropped into the upload area, everything works great.

However, if I accidentally drop the file outside of the upload area, the browser loads the local file as if it is a new page.

How can I prevent this behavior?

Thanks!

Answer

Digital Plane picture Digital Plane · Jul 20, 2011

You can add a event listener to the window that calls preventDefault() on all dragover and drop events.
Example:

window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);