The DataTransferItemList
object is a list of DataTransferItem
objects representing items being dragged. During a drag operation, each DragEvent
has a dataTransfer
property and that property is a DataTransferItemList
.
The individual items can be accessed using the bracket notation []
.
This interface has no constructor.
This example shows how to use drag and drop.
function dragstartHandler(ev) {
console.log("dragStart");
const dataList = ev.dataTransfer.items;
dataList.add(ev.target.id, "text/plain");
dataList.add("<p>Paragraph…</p>", "text/html");
dataList.add("http://www.example.org", "text/uri-list");
}
function dropHandler(ev) {
console.log("Drop");
ev.preventDefault();
for (const item of ev.dataTransfer.items) {
if (item.kind === "string" && item.type.match(/^text\/plain/)) {
item.getAsString((s) => {
ev.target.appendChild(document.getElementById(s));
});
} else if (item.kind === "string" && item.type.match(/^text\/html/)) {
item.getAsString((s) => {
console.log(`… Drop: HTML = ${s}`);
});
} else if (item.kind === "string" && item.type.match(/^text\/uri-list/)) {
item.getAsString((s) => {
console.log(`… Drop: URI = ${s}`);
});
}
}
}
function dragoverHandler(ev) {
console.log("dragOver");
ev.preventDefault();
ev.dataTransfer.dropEffect = "move";
}
function dragendHandler(ev) {
console.log("dragEnd");
const dataList = ev.dataTransfer.items;
dataList.clear();
}
<div>
<p
id="source"
ondragstart="dragstartHandler(event);"
ondragend="dragendHandler(event);"
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"
ondrop="dropHandler(event);"
ondragover="dragoverHandler(event);">
Drop Zone
</div>
div {
margin: 0em;
padding: 2em;
}
#source {
color: blue;
border: 1px solid black;
}
#target {
border: 1px solid black;
}