Drag and Drop API
Which event normally needs preventDefault to make a drop target accept a drop?
Understand the topic
HTML drag and drop uses draggable elements, drag events, and a DataTransfer object. A drop target normally cancels dragover to allow dropping. Dragging is not equally convenient on touch devices or with a keyboard, so offer another way to perform the action. Treat transferred data as untrusted and do not insert it directly as HTML.
Worked example
<p id="item" draggable="true">HTML lesson</p>
<button type="button" id="move">Move lesson to completed</button>
<section id="drop" style="border: 2px dashed #64748b; padding: 1rem;"><h2>Completed</h2></section>
<script>
const item = document.querySelector("#item"), target = document.querySelector("#drop");
const move = () => target.append(item);
item.addEventListener("dragstart", e => e.dataTransfer.setData("text/plain", item.id));
target.addEventListener("dragover", e => e.preventDefault());
target.addEventListener("drop", e => { e.preventDefault(); if (e.dataTransfer.getData("text/plain") === item.id) move(); });
document.querySelector("#move").addEventListener("click", move);
</script>
The button and drag interaction perform the same action. The target only accepts the known item identifier rather than arbitrary markup.
Practice
Which event normally needs preventDefault to make a drop target accept a drop?
Show a suggested answer
dragover. The drop handler should also prevent the default browser action and validate the transferred data.Common mistake
Do not make dragging the only way to move an item. Include a keyboard-accessible command.