Drag Drop in HTML
?? Drag and Drop in HTML
Drag and Drop lets users click on an element, drag it, and drop it somewhere else on the page. It’s commonly used in interactive UIs like file uploaders, sortable lists, or games.
How to Implement Drag and Drop in HTML + JavaScript
Step 1: Make an element draggable
Add the attribute draggable="true" to the HTML element.
<div id="drag1" draggable="true">Drag me!</div>Step 2: Handle Drag Events with JavaScript
You need to listen to events like:
dragstart— when dragging startsdragover— when dragged item is over a drop target (must prevent default to allow drop)drop— when item is dropped
Basic Example
<!DOCTYPE html><html><head> <style> #drag1 { width: 100px; height: 100px; background-color: lightblue; cursor: move; } #dropzone { width: 150px; height: 150px; border: 2px dashed #ccc; margin-top: 20px; } </style></head><body><div id="drag1" draggable="true">Drag me!</div><div id="dropzone">Drop here</div><script> const dragItem = document.getElementById('drag1'); const dropZone = document.getElementById('dropzone'); dragItem.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', e.target.id); }); dropZone.addEventListener('dragover', (e) => { e.preventDefault(); // Necessary to allow drop }); dropZone.addEventListener('drop', (e) => { e.preventDefault(); const id = e.dataTransfer.getData('text'); const draggedElement = document.getElementById(id); dropZone.appendChild(draggedElement); });</script></body></html>Explanation
The draggable div (
drag1) can be dragged.On
dragstart, we store the element’s ID in the drag data.The drop zone (
dropzone) listens fordragover(prevents default behavior so drop is allowed).On
drop, the dragged element is appended to the drop zone.