Lesson 58 +10 XP

HTML Drag and Drop

HTML Drag and Drop

Drag and Drop lets users grab things with the mouse and drop them somewhere. It's how you drag files into an upload box!

The big idea

Any element can be made draggable, and any element can be a "drop zone." JavaScript handles the moving.

Step 1: Make something draggable

Set the draggable attribute and handle the ondragstart event:

<img id="drag1" src="star.png" alt="A star" draggable="true" ondragstart="drag(event)">

Step 2: Choose a drop zone

A drop zone handles ondragover (allow dropping) and ondrop (do something when dropped):

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

Step 3: The JavaScript

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

Let's break it down:

  • allowDrop: calls preventDefault() so the browser lets things drop here.
  • drag: saves what's being dragged (dataTransfer.setData).
  • drop: gets the saved data, finds the element, and moves it in.

DataTransfer: the delivery truck

dataTransfer is like a delivery truck that carries data from the drag start to the drop.

  • setData("text", id): pack the truck.
  • getData("text"): unpack it at the drop.

A full example

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"
     style="width:100px;height:100px;border:2px solid black;"></div>

<script>
function allowDrop(ev) { ev.preventDefault(); }
function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>

<img src="star.png" alt="A star" draggable="true" ondragstart="drag(event)" id="drag1">

TL;DR

  • draggable="true" makes an element draggable.
  • ondragstart saves what's dragged.
  • ondragover must preventDefault() to allow dropping.
  • ondrop moves the element to the drop zone.
  • dataTransfer carries the data.