Course contentsShow
← Web Development
Lesson 2678 of 2,98248. File Uploads and HandlingFree lesson

The drop Event and DataTransfer

Capturing the drop event and accessing files through the DataTransfer object's files property.

The drop Event and DataTransfer

You'll learn how to capture the drop event and extract files from the DataTransfer object when users drag and drop onto your page.

The Drop Event

When a user releases their mouse after dragging files over your drop zone, the drop event fires. This is your moment to capture what was dropped and process those files.

Unlike dragenter and dragover (which you've already seen), the drop event gives you actual access to the dropped data through the DataTransfer object.

The DataTransfer Object

Think of DataTransfer as a package delivery box. When someone drops files onto your drop zone, they arrive inside this box. You access the box through event.dataTransfer, and the files themselves live in its files property.

The files property is a FileList (just like you get from a file input element) containing all the dropped files.

Handling the Drop

Here's the pattern you'll use:

dropZone.addEventListener('drop', (event) => {
  event.preventDefault(); // Stop browser from opening the file
  
  const files = event.dataTransfer.files;
  
  // Now you have access to dropped files
  console.log(`${files.length} file(s) dropped`);
  
  // Iterate through files
  for (const file of files) {
    console.log(file.name, file.type, file.size);
  }
});

Always call event.preventDefault() in the drop handler, or the browser will try to navigate to the dropped file instead of letting your code handle it.

Key Takeaway: The drop event fires when users release dragged items over your drop zone, and event.dataTransfer.files gives you a FileList of the dropped files—just like a file input's files property.