0

I have a HTML file that has a drop zone for someone to drop a file into and a javascript to process that file. dragenter, dragover, and other events work fine but the drop event does not detect that a file was dropped into the area. Any ideas?

drag.js


let dropArea=document.getElementById("dropZone");
dropArea.addEventListener("drop",function() {
    console.log("File entered");
});


index.html

<!DOCTYPE html>
<html>
  <head>
    <title>sample/title>
    <link rel="stylesheet" type="text/css" href="./style.css" media="screen" />
  </head>
  <body>
    <h1>sample1 </h1>

    <h2>Enter target file name</h2>
    <input id="testForm"></input>
    <button id="myButton">scan</button>
    <div id="dropZone" class="dropZone" >
      <p>Drag your files here</p>
  </div>
    
  </body>
</html>


<script src="index.js"></script>
<script src="drag.js"></script>

I will include the css file as well for continuity sake. style.css

#dropZone{
    background-color: rgb(150, 150, 252);
    color:black;
    text-align: center;
    width:300px;
    height:300px;
}
  • Does this answer your question? [Drop event not firing in chrome](https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) – snwflk Feb 22 '22 at 11:47

1 Answers1

0

There are 2 ways to register event listeners in JavaScript:

  1. element.oneventname = function(e) { ... }
  2. element.addEventListener("eventname", function(e) { ... });

You're using option 2, so don't include "on":

dropArea.addEventListener("drop", function() {
  console.log("File entered");
});

Another problem:
Your script tags belong inside the body tag, right before the closing:

    ...
    <script src="index.js"></script>
    <script src="drag.js"></script>
  </body>
</html>
code
  • 5,690
  • 4
  • 17
  • 39