0

How do I listen for drop of files on a whole page? I have tried something like this to stop drop (using document, document.body, window...):

document.addEventListener("drop", evt => {
  evt.preventDefault(); 
  evt.stopPropagation(); 
  console.log("drop", evt);
  debugger; 
})

It does not work as I expected. If I drop an audio file on the page it will open and play.

Leo
  • 4,136
  • 6
  • 48
  • 72
  • The surprising solution is that you need both "drop" and "dragover", see https://stackoverflow.com/questions/6756583/prevent-browser-from-loading-a-drag-and-dropped-file – Leo Apr 27 '20 at 22:39
  • And that is of course a very clumsy solution. A better solutions seems to come with CSS4. – Leo Apr 28 '20 at 09:23

1 Answers1

0

In this case you need the listener "dropend" which will listen when the drop is finished in some element.

window.addEventListener("dragend", () => {
 alert("element throw in the window")
})
#draggable {
    width: 200px;
    height: 20px;
    text-align: center;
    background: white;
  }

  .dropzone {
    width: 200px;
    height: 20px;
    background: blueviolet;
    margin-bottom: 10px;
    padding: 10px;
  }
<div class="dropzone">
    <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
        Drag to the white zone
    </div>
</div>
Oscar Velandia
  • 1,157
  • 1
  • 7
  • 9