Drop API HTML
Drop API HTML
❮ PreviousNext ❯
Example
Browser Support
The numbers in the table specify the first browser version that fully supports
Drag and Drop.
API
Example
<!DOCTYPE HTML>
<html>
<head>
<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>
</head>
<body>
</body>
</html>
Try it Yourself »
It might seem complicated, but lets go through all the different parts of a drag
and drop event.
ADVERTISEMENT
<img draggable="true">
The dataTransfer.setData() method sets the data type and the value of the
dragged data:
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
In this case, the data type is "text" and the value is the id of the draggable
element ("drag1").
event.preventDefault()
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Code explained:
More Examples
Example
How to drag (and drop) an image back and forth between two <div> elements: