HTML Drag and Drop
HTML5 drag-and-drop lets you make any element draggable and any other element a drop target. The browser handles the visual drag preview; you handle what happens on drop.
Three pieces
- Make it draggable. Add
draggable="true"to the element. - Listen for drag events.
dragstart,dragendon the source;dragover,dropon the target. - Pass data via
dataTransfer. Set it indragstart, read it indrop.
Drag-and-drop events
| Event | Fires on | Use for |
|---|---|---|
dragstart | The source | Set data on event.dataTransfer. |
dragover | The target | Call event.preventDefault() to allow drop. |
dragenter / dragleave | The target | Highlight / unhighlight on hover. |
drop | The target | Read data from event.dataTransfer and act on it. |
dragend | The source | Clean up after the operation finishes. |
Minimal example
// HTML: <div id="src" draggable="true">Drag me</div>
// <div id="dest">Drop here</div>
src.addEventListener('dragstart', e => e.dataTransfer.setData('text', src.id));
dest.addEventListener('dragover', e => e.preventDefault());
dest.addEventListener('drop', e => {
e.preventDefault();
const id = e.dataTransfer.getData('text');
dest.appendChild(document.getElementById(id));
});
Tip: For drag-and-drop file uploads, listen for
drop on a target and read event.dataTransfer.files — a FileList identical to the one you'd get from an <input type="file">.Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Drag and Drop</title>
</head>
<body>
<h1>HTML Drag and Drop</h1>
<p>This is a demo page for the "HTML Drag and Drop" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Make this element draggable with one attribute.
<div
="true">Drag me</div>
Nine letters. The boolean-style attribute set to "true".
Discussion
Loading…