The DataTransfer.setData()
method sets the drag operation's drag data
to the specified data and type. If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types
list will be the new type. If data for the given type already exists, the existing data is replaced in the same position. That is, the order of the types
list is not changed when replacing data of the same type.
Example data types are text/plain
and text/uri-list
.
In this example we can drag a <p>
element into a target <div>
element.
- In the
dragstart
handler, we use setData()
to add the id
of the <p>
element to the DataTransfer
object. - In the
drop
handler we retrieve the id
and use it to move the <p>
element into the target.
HTML
<div>
<p id="source" draggable="true">
Select this element, drag it to the drop zone and then release the selection
to move the element.
</p>
</div>
<div id="target">Drop Zone</div>
<button id="reset">Reset example</button>
CSS
div {
margin: 0.5em 0;
padding: 2em;
}
#target,
#source {
border: 1px solid black;
padding: 0.5rem;
}
.dragging {
background-color: pink;
}
JavaScript
const source = document.querySelector("#source");
source.addEventListener("dragstart", (ev) => {
console.log("dragStart");
ev.currentTarget.classList.add("dragging");
ev.dataTransfer.clearData();
ev.dataTransfer.setData("text/plain", ev.target.id);
});
source.addEventListener("dragend", (ev) =>
ev.target.classList.remove("dragging"),
);
const target = document.querySelector("#target");
target.addEventListener("dragover", (ev) => {
console.log("dragOver");
ev.preventDefault();
});
target.addEventListener("drop", (ev) => {
console.log("Drop");
ev.preventDefault();
const data = ev.dataTransfer.getData("text");
const source = document.getElementById(data);
ev.target.appendChild(source);
});
const reset = document.querySelector("#reset");
reset.addEventListener("click", () => document.location.reload());
Result