dragover and drop Events
Define valid drop targets and handle the drop event.
Drop Targets Need Two Handlers
A drop target must handle both dragover (to allow the drop) and drop (to receive it). Without dragover the browser refuses to fire drop because the default behavior is "no element is a drop target".
preventDefault is Mandatory
In the dragover handler you must call e.preventDefault(). This cancels the browser default that rejects the drop. Without it the cursor stays "not allowed" and the drop event never fires no matter what the user does.
zone.addEventListener("dragover", (e) => {
e.preventDefault();
});
zone.addEventListener("drop", (e) => {
e.preventDefault();
console.log(e.dataTransfer.getData("text/plain"));
});All lessons in this course
- draggable Attribute and dragstart Event
- dragover and drop Events
- dataTransfer Object
- Practical Drag-to-Reorder List