Reading history

JavaScript Drag and Drop: Lists and File Uploads

7 min read 1 views

Use the HTML Drag and Drop API to move items between lists and build a file drop zone, with dataTransfer, the key drag events and accessible alternatives.

Dragging cards between columns, reordering a list, and dropping a photo onto an upload box all feel natural to users. Browsers have a built-in Drag and Drop API for this, based on a handful of events such as dragstart, dragover and drop. This lesson builds two working examples: moving items between lists, and a file drop zone. It also explains the one line most beginners forget, and why drag and drop should never be the only way to do something.

In this lesson you will learn

  • Making elements draggable with draggable="true"
  • The drag events and which element receives each one
  • Passing data with dataTransfer
  • Accepting dropped files from the computer
  • Keyboard and touch alternatives

You should know events and DOM manipulation.

Moving Items Between Lists

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Drag and drop between lists</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    .zones { display: flex; gap: 12px; }
    .zone { flex: 1; min-height: 120px; padding: 8px; border: 2px dashed #b0bec5; border-radius: 8px; }
    .zone.over { border-color: #1e88e5; background: #e3f2fd; }
    .item { padding: 6px 8px; margin: 4px 0; background: #fff3e0; border-radius: 4px; cursor: grab; }
    .item.dragging { opacity: 0.4; }
  </style>
</head>
<body>
  <div class="zones">
    <div class="zone" data-zone="todo"><b>To study</b>
      <div class="item" draggable="true" id="i1">Physics: Motion</div>
      <div class="item" draggable="true" id="i2">Chemistry: Atoms</div>
      <div class="item" draggable="true" id="i3">Maths: Sets</div>
    </div>
    <div class="zone" data-zone="done"><b>Finished</b></div>
  </div>
  <p id="status">Drag a topic into the other box.</p>
  <script>
    document.querySelectorAll(".item").forEach(function (item) {
      item.addEventListener("dragstart", function (e) {
        e.dataTransfer.setData("text/plain", item.id);   // what is being dragged
        e.dataTransfer.effectAllowed = "move";
        item.classList.add("dragging");
      });
      item.addEventListener("dragend", function () {
        item.classList.remove("dragging");
      });
    });

    document.querySelectorAll(".zone").forEach(function (zone) {
      zone.addEventListener("dragover", function (e) {
        e.preventDefault();                 // REQUIRED, or dropping is not allowed
        zone.classList.add("over");
      });
      zone.addEventListener("dragleave", function (e) {
        if (!zone.contains(e.relatedTarget)) zone.classList.remove("over");
      });
      zone.addEventListener("drop", function (e) {
        e.preventDefault();
        zone.classList.remove("over");
        var item = document.getElementById(e.dataTransfer.getData("text/plain"));
        if (!item) return;
        zone.append(item);
        document.getElementById("status").textContent =
          item.textContent + " moved to " + zone.dataset.zone;
      });
    });
  </script>
</body>
</html>

Result

  • Links and images can be dragged by default; other elements need draggable="true".
  • dragstart fires on the dragged item. e.dataTransfer.setData("text/plain", item.id) stores which item is moving; it can be read only in the drop event.
  • dragover fires repeatedly on whatever is under the pointer. By default, elements refuse drops, and calling e.preventDefault() here is what makes the zone accept one. Forgetting it is the most common reason drop never fires.
  • drop reads the id back, finds the element and appends it to the zone, which moves it.
  • dragleave also fires when the pointer moves onto a child of the zone. Checking zone.contains(e.relatedTarget) stops the highlight flickering.
  • dragend fires on the dragged item when the drag finishes, whether or not it was dropped, so it is the place to clean up.

A File Drop Zone

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>File drop zone</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    #drop { padding: 24px; text-align: center; border: 2px dashed #9e9e9e; border-radius: 10px; color: #616161; }
    #drop.over { border-color: #43a047; background: #e8f5e9; color: #1b5e20; }
    li { font-family: monospace; font-size: 13px; }
  </style>
</head>
<body>
  <div id="drop">Drop files here</div>
  <p><label>Or choose files: <input type="file" id="pick" multiple></label></p>
  <ul id="files"></ul>
  <script>
    var drop = document.getElementById("drop");
    var out = document.getElementById("files");

    function showFiles(fileList) {
      out.textContent = "";
      Array.from(fileList).forEach(function (file) {
        var li = document.createElement("li");
        var kb = (file.size / 1024).toFixed(1);
        li.textContent = file.name + " — " + kb + " KB — " + (file.type || "unknown type");
        if (file.size > 2 * 1024 * 1024) li.textContent += " (too big: limit 2 MB)";
        out.append(li);
      });
    }

    ["dragenter", "dragover"].forEach(function (type) {
      drop.addEventListener(type, function (e) {
        e.preventDefault();                  // stop the browser opening the file
        drop.classList.add("over");
      });
    });
    ["dragleave", "drop"].forEach(function (type) {
      drop.addEventListener(type, function () { drop.classList.remove("over"); });
    });
    drop.addEventListener("drop", function (e) {
      e.preventDefault();
      showFiles(e.dataTransfer.files);       // a FileList, like input.files
    });
    document.getElementById("pick").addEventListener("change", function (e) {
      showFiles(e.target.files);             // the keyboard-friendly alternative
    });
  </script>
</body>
</html>

Result

  • When files are dragged in from the computer, the browser would normally open them, replacing your page. Calling preventDefault() on dragenter, dragover and drop stops that.
  • e.dataTransfer.files is a FileList, the same type as an <input type="file">‘s files, so one function, showFiles, handles both.
  • Each File has a name, size in bytes and type such as image/png. Check size and type before uploading, though the server must check again.
  • The visible file input is not optional: it is the way in for keyboard users, screen reader users and many phones.
  • To upload, add the files to a FormData object and send it with fetch; to preview an image, use URL.createObjectURL(file).

Drag Events Reference

EventFires onTypical use
dragstartDragged elementStore data, style the item
dragenter / dragoverElement under the pointerpreventDefault() to allow a drop; highlight
dragleaveElement the pointer leftRemove the highlight
dropDrop targetRead data and move or upload
dragendDragged elementClean up styles

Accessibility and Touch

Drag and drop needs a mouse or a precise finger, and on touch screens the built-in API works only in recent mobile browsers. Always offer another way to do the same job: “Move to…” buttons, a select menu, or arrow buttons, as the Kanban board project does. For complex touch-friendly sorting, many sites use pointer events or a library built on them.

Common Mistakes

  1. Not calling preventDefault() in dragover, so drop never fires.
  2. Trying to read getData in dragover. For security, the data is readable only on drop.
  3. Forgetting preventDefault() in drop for files, so the browser opens the file.
  4. Making drag and drop the only option, shutting out keyboard and many mobile users.

Practice Exercises

Exercise 1. In the list example, show how many items are in the “Finished” box after every drop.

Show answer
// inside the drop handler, after zone.append(item)
const done = document.querySelector('[data-zone="done"]');
document.getElementById("status").textContent +=
  " (" + done.querySelectorAll(".item").length + " finished)";

Exercise 2. Change the file drop zone so it accepts only images and ignores other files.

Show answer
const images = Array.from(fileList).filter(f => f.type.startsWith("image/"));
// then loop over images instead of fileList
// and add accept="image/*" to the file input

Frequently Asked Questions

How do I reorder items within one list?

In dragover, find the item under the pointer and compare the pointer’s Y position with the middle of that item. Insert the dragged element before or after it with before() or after().

Can I change the image shown while dragging?

Yes. In dragstart, call e.dataTransfer.setDragImage(element, x, y) with any visible element or image to use as the drag preview.

Summary

  • Make items draggable, store data in dragstart and read it in drop.
  • preventDefault() in dragover allows a drop.
  • dataTransfer.files gives dropped files, just like a file input.
  • Always provide a keyboard and touch-friendly alternative.

Next: Copying Objects: Shallow vs Deep Copy.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *