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.
Creating a functioning drag-and-drop system requires three specific steps to wire the HTML elements together using JavaScript event attributes.
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>
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>
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>
Try it yourself! Click and hold the blue square, then drag it into the empty box on the right.