Drag and Drop Events in JavaScript
Build drag and drop in JavaScript with the HTML5 API, dataTransfer, a custom mouse and touch drag, position limits and a sortable list. Explanation and output.
This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add #draggable, #dropzone, an absolutely positioned #customDraggable, and a <ul id="sortableList"> whose <li> items have draggable="true".
1// Method 1: HTML5 Drag and Drop API2const draggable = document.getElementById('draggable');3const dropzone = document.getElementById('dropzone');45// Make element draggable6draggable.draggable = true;78// Drag events on source9draggable.addEventListener('dragstart', function(e) {10 console.log('Drag started');11 e.dataTransfer.setData('text/plain', draggable.id);12 e.dataTransfer.effectAllowed = 'move';13 draggable.style.opacity = '0.5';14});1516draggable.addEventListener('dragend', function(e) {17 console.log('Drag ended');18 draggable.style.opacity = '1';19});2021// Drop events on target22dropzone.addEventListener('dragover', function(e) {23 e.preventDefault(); // Allow drop24 e.dataTransfer.dropEffect = 'move';25 dropzone.style.backgroundColor = 'lightblue';26});2728dropzone.addEventListener('dragleave', function(e) {29 dropzone.style.backgroundColor = '';30});3132dropzone.addEventListener('drop', function(e) {33 e.preventDefault();34 console.log('Dropped');35 const data = e.dataTransfer.getData('text/plain');36 const element = document.getElementById(data);37 dropzone.appendChild(element);38 dropzone.style.backgroundColor = '';39});4041// Method 2: Custom drag implementation42let isDragging = false;43let currentX, currentY, initialX, initialY;4445const customDraggable = document.getElementById('customDraggable');4647customDraggable.addEventListener('mousedown', function(e) {48 isDragging = true;49 initialX = e.clientX - customDraggable.offsetLeft;50 initialY = e.clientY - customDraggable.offsetTop;51 customDraggable.style.cursor = 'grabbing';52});5354document.addEventListener('mousemove', function(e) {55 if (isDragging) {56 e.preventDefault();57 currentX = e.clientX - initialX;58 currentY = e.clientY - initialY;5960 customDraggable.style.left = currentX + 'px';61 customDraggable.style.top = currentY + 'px';62 }63});6465document.addEventListener('mouseup', function() {66 if (isDragging) {67 isDragging = false;68 customDraggable.style.cursor = 'grab';69 }70});7172// Method 3: Drag with touch support73customDraggable.addEventListener('touchstart', function(e) {74 isDragging = true;75 const touch = e.touches[0];76 initialX = touch.clientX - customDraggable.offsetLeft;77 initialY = touch.clientY - customDraggable.offsetTop;78});7980document.addEventListener('touchmove', function(e) {81 if (isDragging) {82 e.preventDefault();83 const touch = e.touches[0];84 currentX = touch.clientX - initialX;85 currentY = touch.clientY - initialY;8687 customDraggable.style.left = currentX + 'px';88 customDraggable.style.top = currentY + 'px';89 }90});9192document.addEventListener('touchend', function() {93 isDragging = false;94});9596// Method 4: Drag with constraints97function dragWithConstraints(element, minX, minY, maxX, maxY) {98 let isDragging = false;99 let startX, startY, offsetX, offsetY;100101 element.addEventListener('mousedown', function(e) {102 isDragging = true;103 startX = e.clientX;104 startY = e.clientY;105 offsetX = element.offsetLeft;106 offsetY = element.offsetTop;107 });108109 document.addEventListener('mousemove', function(e) {110 if (isDragging) {111 let newX = offsetX + (e.clientX - startX);112 let newY = offsetY + (e.clientY - startY);113114 // Apply constraints115 newX = Math.max(minX, Math.min(maxX, newX));116 newY = Math.max(minY, Math.min(maxY, newY));117118 element.style.left = newX + 'px';119 element.style.top = newY + 'px';120 }121 });122123 document.addEventListener('mouseup', function() {124 isDragging = false;125 });126}127128// Method 5: Sortable list129const sortableList = document.getElementById('sortableList');130131sortableList.addEventListener('dragstart', function(e) {132 if (e.target.tagName === 'LI') {133 e.target.classList.add('dragging');134 e.target.style.opacity = '0.5';135 e.dataTransfer.effectAllowed = 'move';136 e.dataTransfer.setData('text/html', e.target.innerHTML);137 }138});139140sortableList.addEventListener('dragend', function(e) {141 if (e.target.tagName === 'LI') {142 e.target.classList.remove('dragging');143 e.target.style.opacity = '1';144 }145});146147sortableList.addEventListener('dragover', function(e) {148 e.preventDefault();149 const afterElement = getDragAfterElement(sortableList, e.clientY);150 const dragging = sortableList.querySelector('.dragging');151 if (!dragging) return;152153 if (afterElement == null) {154 sortableList.appendChild(dragging);155 } else {156 sortableList.insertBefore(dragging, afterElement);157 }158});159160function getDragAfterElement(container, y) {161 const draggableElements = [...container.querySelectorAll('li:not(.dragging)')];162163 return draggableElements.reduce((closest, child) => {164 const box = child.getBoundingClientRect();165 const offset = y - box.top - box.height / 2;166167 if (offset < 0 && offset > closest.offset) {168 return { offset: offset, element: child };169 } else {170 return closest;171 }172 }, { offset: Number.NEGATIVE_INFINITY }).element;173}
Sample Output
Dropped
Printed before Drag ended, because drop fires on the target first.
In this one
- The HTML5 drag and drop events
- Why dragover must call preventDefault
- How dataTransfer passes data
- How to build a custom drag and a sortable list
How it works
- 1
dragstart stores the id and fades the item.
- 2
dragover allows the drop and highlights the zone.
- 3
drop reads the id and moves the element into the zone.
- 4
Custom mouse and touch handlers move a box by style.left and top.
- 5
dragWithConstraints clamps the position.
- 6
The sortable list marks the dragged item and reorders it on dragover.
Edge cases
Drop never fires
The dragged item snaps back.
Call e.preventDefault() inside dragover.
Element does not move
style.left has no effect.
Give the element position: absolute or relative.
Mobile
The HTML5 drag API does not work on most phones.
Use the touch version or pointer events.
What's going on
Drag and drop lets users pick something up and move it. File uploads, sortable lists and card boards like a class timetable all use it.
Method 1 uses the HTML5 Drag and Drop API. Setting draggable = true lets an element be dragged. On the source, dragstart fires when the drag begins and dragend when it ends. On the target, dragover fires while the item is over it, dragleave when it leaves, and drop when it is released.
dragover needs e.preventDefault(). Without it, the browser refuses the drop and the drop event never fires. This is the most common bug.
The dataTransfer object carries data during the drag. setData('text/plain', id) stores the element id at the start. getData reads it on drop. effectAllowed says what is allowed, such as move. dropEffect sets the visual feedback. The code also changes opacity and background colour as visual feedback.
Method 2 builds drag by hand with mouse events. mousedown remembers where you grabbed the box. mousemove on document moves it with style.left and style.top. mouseup stops. The element needs position: absolute for left and top to work.
Method 3 adds touch support with the same idea, using touches[0].
Method 4 adds limits. Math.max(minX, Math.min(maxX, newX)) clamps the value, which means it keeps it inside a range.
Method 5 is a sortable list. getDragAfterElement finds the item just below the mouse by comparing positions from getBoundingClientRect. The dragged item is then inserted before it. dragstart adds a .dragging class and dragend removes it. getDragAfterElement uses that class to find the item being moved.
Best practices: give visual feedback, support touch, add limits, and test keyboard access, because drag and drop alone is hard for some users.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which event must call preventDefault to allow a drop?
Pick an answer to check it.
Question 2
What does setData store?
Pick an answer to check it.
Questions people ask
Why store the id instead of the element?
dataTransfer only stores strings.
What does clamping mean?
Keeping a value between a minimum and maximum.
Is drag and drop accessible?
Not by default. Add buttons or keyboard controls as another option.