Search code examples
javascripthtmldrag-and-dropfileapi

Disable dragging of a file system image into a browser.


I am experimenting with the HTML5 file API. I notice however that browsers have a default behaviour where they display an image if you drag the image into the browser. This can however be annoying if your aim is to upload the image rather than to view it.

I am wondering if there is a way of preventing this behaviour? I have tried stopPropagation / preventDefault on an ondrop event which works somewhat, however leaves the "drop" cursor in place giving the impression that the image can be dropped anywhere on the page.

Ideally you would only see the "drop" cursor on the designated area where images are meant to be dropped.


Solution

  • The dataTransfer object has dropEffect and effectAllowed properties. Not exactly sure what the difference between them, but setting both to 'none' should help.

    $(document).bind({
       dragenter: function (e) {
          e.stopPropagation();
          e.preventDefault();
          var dt = e.originalEvent.dataTransfer;
         dt.effectAllowed = dt.dropEffect = 'none';
       },
       dragover: function (e) {
          e.stopPropagation();
          e.preventDefault();
          var dt = e.originalEvent.dataTransfer;
          dt.effectAllowed = dt.dropEffect = 'none';
       }
    });
    

    See the http://jsfiddle.net/andreymir/H3RR7/embedded/result/ - drop allowed to rectangle only.