HTML Drag and Drop

The HTML5 Drag and Drop API lets users grab an element with the mouse, drag it across the page, and drop it onto another element. It's built on the draggable attribute plus a small set of drag events.

1) The draggable Attribute


<div id="box" draggable="true">Drag me</div>

Most elements aren't draggable by default. Setting draggable="true" makes an element pick-up-able by the mouse.

2) ondragstart — Starting the Drag


<div id="box" draggable="true" ondragstart="drag(event)">Drag me</div>

<script>
function drag(event) {
  // Store the dragged element's id so the drop handler knows what to move
  event.dataTransfer.setData("text/plain", event.target.id);
}
</script>

event.dataTransfer.setData(type, data) attaches data to the drag operation — commonly the dragged element's id.

3) ondragover — Allowing a Drop


<div id="dropzone" ondragover="allowDrop(event)">Drop here</div>

<script>
function allowDrop(event) {
  event.preventDefault(); // required! by default, dropping is not allowed
}
</script>

By default, browsers block dropping on most elements. Calling event.preventDefault() inside ondragover is what tells the browser "this element accepts drops."

4) ondrop — Handling the Drop


<div id="dropzone" ondragover="allowDrop(event)" ondrop="drop(event)">Drop here</div>

<script>
function drop(event) {
  event.preventDefault();
  var draggedId = event.dataTransfer.getData("text/plain");
  var draggedEl = document.getElementById(draggedId);
  event.target.appendChild(draggedEl); // actually moves the element
}
</script>

event.dataTransfer.getData() retrieves what was stored in ondragstart, and appendChild() physically moves the dragged element into the drop zone.

5) Putting It All Together


<div id="dropzone" ondragover="allowDrop(event)" ondrop="drop(event)">Drop Zone</div>
<div id="drag1" draggable="true" ondragstart="drag(event)">Drag me</div>

<script>
function allowDrop(event) { event.preventDefault(); }

function drag(event) {
  event.dataTransfer.setData("text/plain", event.target.id);
}

function drop(event) {
  event.preventDefault();
  var id = event.dataTransfer.getData("text/plain");
  event.target.appendChild(document.getElementById(id));
}
</script>

Live Demo

Drag the blue box into the dashed drop zone:

Drag me
Drop here

Best Practices:

  • You must call event.preventDefault() inside ondragover, or the browser will refuse the drop entirely.
  • Use event.dataTransfer to pass information (like an element's id) from the drag source to the drop target.
  • The Drag and Drop API is primarily mouse-based; for touch devices, test carefully or provide an alternative interaction.
  • Give visual feedback (e.g. a highlighted border) on the drop zone during dragover to make the interaction clearer to users.