HTML Drag and Drop with Data Transfer
The HTML5 Drag and Drop API also allows you to transfer custom data between draggable and drop zones using the dataTransfer object. Here's an example:
<div id="dragElement" draggable="true" ondragstart="dragStart(event)">Drag me</div>
<div id="dropZone" ondrop="drop(event)" ondragover="allowDrop(event)">Drop here</div>
<script>
function dragStart(event) {
event.dataTransfer.setData("text/plain", event.target.id);
event.dataTransfer.effectAllowed = "move";
}
function allowDrop(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
const data = event.dataTransfer.getData("text/plain");
const draggedElement = document.getElementById(data);
event.target.appendChild(draggedElement);
}
</script>
No comments:
Post a Comment