HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

HTML Drag & Drop

Before HTML5, creating a drag-and-drop interface on a website required thousands of lines of complex JavaScript math to manually calculate mouse coordinates. Now, HTML5 includes a native Drag and Drop (DnD) API that makes this incredibly simple.

Any element on an HTML page can be made draggable, allowing users to "grab" an object, drag it across the screen, and "drop" it into a new target zone.


The 1-2-3 of Drag & Drop

Creating a functioning drag-and-drop system requires three specific steps to wire the HTML elements together using JavaScript event attributes.

Step 1: Make it Draggable

First, you must explicitly tell the browser that an element is allowed to be picked up by adding the draggable="true" attribute to the HTML tag. You must also assign a function to the ondragstart event to define exactly what data is being dragged.

<!-- Making a div draggable -->
<div id="my-box" draggable="true" ondragstart="drag(event)">
  Drag me!
</div>

<script>
function drag(ev) {
  // We save the ID of the dragged element into the data transfer buffer
  ev.dataTransfer.setData("text", ev.target.id);
}
</script>

Step 2: Create a Drop Zone

By default, web browsers refuse to let you drop things randomly on the page. To create a valid target zone where an item can be dropped, you must override this default behavior using the ondragover event.

<!-- A box that accepts dropped items -->
<div id="drop-zone" ondragover="allowDrop(event)" ondrop="drop(event)"></div>

<script>
function allowDrop(ev) {
  // This turns off the browser's default restriction
  ev.preventDefault();
}
</script>

Step 3: Handle the Drop

Finally, when the user releases their mouse over the target zone, the ondrop event fires. We grab the data we saved in Step 1 (the ID) and append that element into the new drop zone.

<script>
function drop(ev) {
  ev.preventDefault();
  
  // Retrieve the ID we saved earlier ("my-box")
  var data = ev.dataTransfer.getData("text");
  
  // Actually move the element into the new zone
  ev.target.appendChild(document.getElementById(data));
}
</script>

Interactive Example

Try it yourself! Click and hold the blue square, then drag it into the empty box on the right.

Drag Me!
Drop Here