Skip to content
","url":"https://ez4code.com/snippets/html5-drag-drop","keywords":"drag-drop, files","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
HTML5

Drag and Drop

Accept dropped files with the Drag and Drop API.

By EZ4Code Team
drag-dropfiles

Code

<div id="drop" style="width:200px;height:100px;border:2px dashed #999">
  Drop files here
</div>

<script>
  const drop = document.getElementById("drop");

  drop.addEventListener("dragover", e => {
    e.preventDefault();            // allow drop
    drop.classList.add("over");
  });

  drop.addEventListener("dragleave", () => {
    drop.classList.remove("over");
  });

  drop.addEventListener("drop", e => {
    e.preventDefault();
    drop.classList.remove("over");
    const files = e.dataTransfer.files;
    for (const file of files) {
      console.log(file.name, file.size, file.type);
    }
  });
</script>

Explanation

The Drag and Drop API fires dragover and drop events on a target; calling preventDefault on dragover is required to allow the drop. The transferred data lives in e.dataTransfer, which holds files for native drag operations. File objects expose name, size, and type for further processing.

More HTML5 Snippets