Drag and Drop Events
You'll learn how to implement drag-and-drop interfaces using the HTML5 drag-and-drop API events.
Drag-and-drop lets users grab an element with their mouse (or finger) and move it to a new location on the page. Think of it like rearranging sticky notes on a board—you pick one up, move it around, and place it somewhere else.
Understanding the Drag-and-Drop Event Flow
The drag-and-drop API involves two types of elements: the draggable item (what you're moving) and the drop zone (where you can place it). Different events fire on each:
Events on the Draggable Element
dragstart: Fires when you begin draggingdrag: Fires continuously while draggingdragend: Fires when the drag operation completes (whether successful or cancelled)
Events on the Drop Zone
dragenter: Fires when a dragged element enters the drop zonedragover: Fires continuously while hovering over the drop zone (must callpreventDefault()to allow dropping)dragleave: Fires when a dragged element leaves the drop zonedrop: Fires when the element is released in the drop zone (must callpreventDefault()ondragoverfirst)
The Critical Detail
To enable dropping, you must call preventDefault() in both the dragover and drop event handlers. Without this, the browser won't allow the drop operation—the element will snap back to its original position.
During dragstart, you typically store data about what's being dragged using event.dataTransfer.setData(), then retrieve it in the drop handler with event.dataTransfer.getData().
Key Takeaway: Drag-and-drop requires coordinating events on both the draggable element (dragstart, dragend) and drop zones (dragover, drop), with preventDefault() being essential to allow the drop operation.