Drag and Drop API
Create intuitive drag and drop interfaces with the HTML5 Drag and Drop API. Build file uploaders, sortable lists, shopping carts, and interactive dashboards.
How does drag and drop work in HTML?
Make an element draggable with draggable="true" and set the data being dragged in its dragstart handler (e.dataTransfer.setData(…)). On the drop target, call e.preventDefault() in dragover to allow dropping, then read the data in the drop event. Dropped files arrive in e.dataTransfer.files.
<div id="card" draggable="true">Drag me</div>
<div id="zone">Drop here</div>
<script>
card.addEventListener("dragstart", e => e.dataTransfer.setData("text/plain", "card"));
zone.addEventListener("dragover", e => e.preventDefault());
zone.addEventListener("drop", e => {
e.preventDefault();
zone.append(document.getElementById(e.dataTransfer.getData("text/plain")));
});
</script>Drag and Drop Concepts
Draggable Elements
- • Add `draggable="true"` attribute
- • Handle `dragstart` event
- • Set data with `dataTransfer`
- • Style dragging state
Drop Zones
- • Prevent default behaviors
- • Handle `dragover` and `drop`
- • Validate dropped data
- • Provide visual feedback
Essential Events
Interactive Drag & Drop Examples
Explore comprehensive drag and drop implementations including file uploads, sortable lists, shopping carts, and kanban boards.
Drag and Drop API Fundamentals
Essential Events
- dragstart: Drag operation begins
- dragover: Dragged item is over target
- dragenter: Dragged item enters target
- dragleave: Dragged item leaves target
- drop: Item dropped on target
- dragend: Drag operation ends
DataTransfer Object
setData()- Store drag datagetData()- Retrieve drag dataclearData()- Clear stored datafiles- Access dropped files
Drop Effects
- copy: Copy the dragged item
- move: Move the dragged item
- link: Create a link to item
- none: No operation allowed
Browser Support
- ✓ Chrome, Firefox, Safari, Edge
- ✓ Mobile support varies
- ✓ Touch events may need polyfills
- ✓ File API integration available
Common Implementation Patterns
File Upload Drop Zone
Key Features
- • Visual feedback on hover
- • File type validation
- • Size limit checking
- • Progress indicators
- • Multiple file support
Best Practices
- • Clear visual drop zone boundaries
- • Prevent default browser behavior
- • Provide fallback file input
- • Show file previews when possible
- • Handle errors gracefully
Sortable Lists & Reordering
Implementation Steps
- 1. Make list items draggable
- 2. Track drag start position
- 3. Handle dragover events
- 4. Calculate insertion point
- 5. Reorder DOM elements
User Experience
- • Visual drag handles
- • Smooth animations
- • Clear insertion indicators
- • Keyboard accessibility
- • Touch device support
Shopping Cart & Product Selection
Drag Operations
- • Product to cart addition
- • Quantity updates via drag
- • Cross-category movement
- • Wishlist interactions
- • Remove via trash zone
Data Management
- • Product ID tracking
- • Price calculations
- • Inventory validation
- • State persistence
- • Real-time updates
Advanced Drag & Drop Techniques
Custom Drag Images
Create custom drag previews using setDragImage():
dragEvent.dataTransfer.setDragImage(customImage, x, y)Multiple Data Types
Store multiple data formats for different drop targets:
- • text/plain for basic text
- • text/html for rich content
- • application/json for objects
- • Custom MIME types
Touch Device Support
Extend drag & drop to touch devices:
- • Use touch event polyfills
- • Implement long-press to drag
- • Visual feedback for touch
- • Gesture recognition
Performance Optimization
- • Throttle dragover events
- • Use document fragments
- • Minimize DOM manipulation
- • Cache element references
- • Debounce expensive operations
Accessibility & User Experience
Keyboard Accessibility
- • Arrow keys for navigation
- • Space/Enter for selection
- • Escape to cancel operation
- • Tab for focus management
- • ARIA live regions for feedback
Screen Reader Support
- • Descriptive ARIA labels
- • Role attributes for draggables
- • Live announcements
- • Alternative interaction methods
- • Clear instructions
Visual Feedback
- • Clear drag handles
- • Hover state indicators
- • Drop zone highlighting
- • Insertion point markers
- • Success/error animations
Error Handling
- • Invalid drop target feedback
- • Operation cancellation
- • Graceful failure recovery
- • User-friendly error messages
- • Fallback interaction methods
Code Editor
<div class="col" id="todo"><h4>To do</h4>
<p class="card" draggable="true" id="c1">Learn HTML</p>
<p class="card" draggable="true" id="c2">Learn CSS</p>
</div>
<div class="col" id="done"><h4>Done</h4></div>Preview
Common Use Cases
File Uploads
- • Drag files from desktop
- • Multiple file selection
- • Progress indicators
- • File type validation
Sortable Lists
- • Reorder items
- • Priority management
- • Visual feedback
- • Touch support
Kanban Boards
- • Task management
- • Status updates
- • Column restrictions
- • Real-time sync
Your Learning Path
Master HTML5 Drag and Drop API for interactive interfaces
What You've Learned
- ▶Drag and drop API fundamentals
- ▶Draggable attribute and events
- ▶Data transfer object usage
- ▶Drop zones and event handling
- ▶File drag and drop implementation
What's Next
- ▶Geolocation API - User location tracking
- ▶Web Storage - Local data persistence
- ▶File API - Advanced file handling
- ▶Canvas API - Interactive graphics
- ▶WebSockets - Real-time communication
Pro Learning Tip
Drag and drop enhances user experience significantly. Practice with different data types, implement visual feedback, and always provide fallback options for touch devices.
HTML Drag and Drop — step by step
Make an element draggable
Add the draggable='true' attribute to any HTML element to make it draggable. Handle the dragstart event to set the data being transferred using event.dataTransfer.setData('text/plain', value).
🎯 Quick Check
What must you call in the dragover event handler to allow an element to accept drops?
HTML Drag and Drop: summary
Key points
- Without
preventDefault()indragover, thedropevent never fires. - Native drag and drop doesn't work with touch on many mobile browsers; use Pointer Events or a library for touch.
- Provide a keyboard alternative, such as move up and down buttons, for accessibility.
Frequently asked questions
›Why isn't my drop event firing?
You must call event.preventDefault() in the dragover handler of the drop target.