Drag and Drop with JavaScript
The Drag and Drop API allows users to drag elements on a webpage and drop them into different locations. It's useful for file uploads, reordering lists, and interactive interfaces.
1️⃣ Basic Drag and Drop Events
The Drag and Drop API provides the following events:
Event | Description |
---|---|
dragstart | Fires when dragging starts |
drag | Fires when the element is being dragged |
dragend | Fires when dragging stops |
dragenter | Fires when the dragged element enters a valid drop target |
dragover | Fires when the element is being dragged over a valid drop target |
dragleave | Fires when the dragged element leaves a drop target |
drop | Fires when the dragged element is dropped |
2️⃣ Basic Example: Dragging an Element
✅ Drag the blue box into the dashed drop area!
3️⃣ Dragging Multiple Elements
If you have multiple draggable elements, use event.target
.
✅ Each draggable element can be moved separately.
4️⃣ Drag and Drop Files
This is useful for uploading files.
✅ Dragging files over the drop zone will log the files in the console.
🔹 Summary
✔ dragstart
and drop
handle dragging elements.
✔ event.dataTransfer
stores dragged data.
✔ event.preventDefault()
allows dropping.
✔ You can drag and drop files into a page.
🚀 Need a more advanced example? Let me know!