JavaScript Notes
Master the HTML5 Drag and Drop API in JavaScript. Learn draggable elements, drop zones, DataTransfer, dragstart/dragover/drop events with real examples and interview Q&A.
The HTML5 Drag and Drop API lets users drag elements (or files) and drop them onto target zones directly in the browser — no libraries required. It powers file upload UIs, Kanban boards, sortable lists, and palette-based tools.
💡 Key insight: Drag-and-drop involves *two* elements: the draggable source and the drop target. They communicate through a shared DataTransfer object and a sequence of events fired on each.The Event Sequence
User presses mouse button on draggable element
│
▼
dragstart ← fires on the SOURCE element
│
▼ (user moves mouse)
drag ← fires repeatedly on SOURCE while dragging
│
▼ (mouse enters a drop target)
dragenter ← fires on TARGET
dragover ← fires repeatedly on TARGET (must call preventDefault!)
dragleave ← fires on TARGET when mouse leaves without dropping
│
▼ (user releases mouse)
drop ← fires on TARGET
dragend ← fires on SOURCE (always, even if drop was cancelled)Making an Element Draggable
"Drag started, carrying ID: card" "Drag ended, dropEffect: move"
Setting Up a Drop Target
"Dropped element with ID: card" // The #card div is now a child of #dropzone in the DOM
The DataTransfer Object
DataTransfer is the messenger between drag source and drop target.
// Writing data (in dragstart)
e.dataTransfer.setData("text/plain", "Hello");
e.dataTransfer.setData("text/html", "<b>Hello</b>");
e.dataTransfer.setData("application/json", JSON.stringify({ id: 42 }));
// Reading data (in drop)
const text = e.dataTransfer.getData("text/plain");
const json = JSON.parse(e.dataTransfer.getData("application/json"));
console.log(text, json);"Hello" { id: 42 }| Property | Purpose |
|---|---|
setData(type, value) | Store data with a MIME type |
getData(type) | Retrieve stored data |
clearData(type) | Remove stored data |
effectAllowed | What drag operations are allowed (copy, move, link, none, all) |
dropEffect | The operation that will happen on drop (copy, move, link, none) |
files | FileList when dragging files from the OS |
Dragging Files from the OS
"Name: photo.jpg, Size: 204800 bytes, Type: image/jpeg" "Name: report.pdf, Size: 512000 bytes, Type: application/pdf"
Practical Example: Sortable List
"New order: ["Item 3", "Item 1", "Item 2"]" // (order depends on where user dropped)
Visual Drag State with CSS
When to Use Drag and Drop
- File upload — drag files from desktop into an upload area
- Kanban boards — move task cards between columns (To Do → In Progress → Done)
- Sortable lists — reorder items by dragging
- Dashboard builders — drag widgets to rearrange layouts
- Colour/palette pickers — drag a swatch onto a target
Common Mistakes
- Forgetting
e.preventDefault()ondragover— the drop will not fire without it. The browser blocks drops by default. - Using
e.targetdirectly indragover— child elements inside the drop zone can become the target. Useclosest()to find the right container. - Setting
draggable="true"on inline elements — works best on block-level elements. Images and links are draggable by default. - Not cleaning up
draggedItemindragend— stale references cause bugs. - Overriding
ondragoveron the wrong element — the handler must be on the drop *target*, not the draggable source. - Expecting drag-and-drop to work on mobile — touch events are separate; use a library like SortableJS for cross-device support.
Interview Questions
Q1. Why must you call e.preventDefault() in the dragover handler?
By default, browsers do not allow elements to be dropped. Callinge.preventDefault()tells the browser that the target element *accepts* drops, enabling thedropevent to fire.
Q2. What is the DataTransfer object?
DataTransferis the object that holds the data being dragged. It allows the drag source tosetData()with a MIME type and value, and the drop target togetData()to read it. It also exposesfileswhen files are dragged from the OS.
Q3. What is the difference between effectAllowed and dropEffect?
effectAllowedis set by the *source* indragstartto declare what operations are permitted (e.g."copy","move").dropEffectis set by the *target* indragoverto declare what operation it will perform. The browser uses both to determine the cursor icon.
Q4. What events fire on the drag source and what fire on the drop target?
Source:dragstart,drag,dragend. Target:dragenter,dragover,dragleave,drop.
Q5. How do you handle file drops from the desktop?
Listen fordropon the target, calle.preventDefault(), then reade.dataTransfer.files— aFileListofFileobjects.
Q6. How do you implement a sortable list with drag and drop?
Store the draggedliindragstart. Indragover, compare the mouse Y position to the target's midpoint usinggetBoundingClientRect(), then useinsertBefore()to reorder the items live.
Q7. Does the native Drag and Drop API work on touch/mobile devices?
No — native DnD uses mouse events and does not fire on touch screens. For mobile, you need a library (e.g., SortableJS, interact.js) that translates touchmove events into equivalent drag behaviour.Key Takeaways
- Drag-and-drop requires *both* a draggable source and a drop target with the correct event listeners.
- Always call
e.preventDefault()indragover— otherwisedropwill never fire. DataTransferis the shared carrier object between source and target — usesetData/getData.- Dragging files from the OS populates
e.dataTransfer.files. - Native DnD does not work on touch devices — use a library for mobile support.
- Apply CSS
cursor: grab,opacity, and border styles to give clear visual feedback.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Drag and Drop API in JavaScript — Complete Tutorial.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, drag
Related JavaScript Master Course Topics