Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding eventListener for file drop

I am learning how to add an EventListener to a <div> so that I can drop a file to it for reading a csv file. Below is my simple HTML code that adds an EventListener, but when I dragged and dropped a file, the Chrome browser keeps downloading the file that I dropped and the console output "hey" is not printed. If anyone could let me know what is wrong I'd greatly appreciate the help. :)

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
<style>
#drop{
  border:2px dashed #bbb;
  -moz-border-radius:5px;
  -webkit-border-radius:5px;
  border-radius:5px;
  padding:25px;
  text-align:center;
  width:128px;
  font:20pt bold,"Vollkorn";color:#bbb
}
</style>
    </head>
    <body>
    <div id="drop">Drop a file here</div>

    <script type="text/javascript">
        var drop_dom_element = document.getElementById('drop');
        var workbook;

        /* set up drag-and-drop event */
        function handleDrop(e) {
          console.log('hello');
          e.stopPropagation();
          e.preventDefault();
          console.log('hey');
        }

        drop_dom_element.addEventListener('drop', handleDrop, false);
        console.log('Done');        
        </script>
    </body>
</html>
like image 901
user1330974 Avatar asked Mar 15 '26 17:03

user1330974


1 Answers

The default behaviour of most (all?) elements is not to allow dropping. Read this MDN article.

A listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped. Most areas of a web page or application are not valid places to drop data. Thus, the default handling of these events is not to allow a drop.

Adding event.preventDefault() to the dragover event seems to do the trick in current versions of Firefox and Chrome.

element.addEventListener("dragover", function( event ) {
  // prevent default to allow drop
  event.preventDefault();
}, false);

Under Performing a Drop:

When the user releases the mouse, the drag and drop operation ends. If the mouse was released over an element that is a valid drop target, that is, one that cancelled the last dragenter or dragover event, and then the drop will be successful, and a drop event will fire at the target. Otherwise, the drag operation is cancelled, and no drop event is fired.


The reason for adding the preventDefault call to the drop event function too is to prevent the default behaviour browsers might have such as immediately opening links and images.

You can see in this jsfiddle that dragging text or images will trigger the drop event, but Firefox and Chrome will also open images and links.

like image 130
pishpish Avatar answered Mar 18 '26 05:03

pishpish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!