JSFiddle - React, Tailwind, and code Playground
HTML
<div class="dragDiv" draggable="true">
<p>Drag Div 01</p>
</div>
<div class="dragDiv" draggable="true">
<p>Drag Div 02</p>
</div>
<div class="dragDiv" draggable="true">
<p>Drag Div 03</p>
</div>
CSS
html, body, p {
margin:0;
padding:0;
}
.dragDiv {
display:table;
width:100px; height:50px;
position:absolute;
background-color:#555555;
}
.dragDiv p {
display:table-cell;
vertical-align:middle;
text-align:center;
font-family:sans-serif;
font-size:15px;
color:#FFFFFF;
}
JavaScript
// global object for storing data
var dragDetails = {
target: null,
orgMouseX: 0,
orgMouseY: 0,
desMouseX: 0,
desMouseY: 0
}
// need this but not sure why
$("html").on("dragover", function(event) {
event.preventDefault();
event.stopPropagation();
});
// need this but not sure why
$("html").on("dragleave", function(event) {
event.preventDefault();
event.stopPropagation();
});
// drag start event
$('[draggable="true"]').on("dragstart", function(event) {
event.stopPropagation();
event.originalEvent.dataTransfer.setData("text", event.target.id);
// store target and current mouse position
dragDetails.target = this;
dragDetails.orgMouseX = event.originalEvent.pageX;
dragDetails.orgMouseY = event.originalEvent.pageY;
});
// drag end event
$("html").on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
// store destination mouse position
dragDetails.desMouseX = event.originalEvent.pageX;
dragDetails.desMouseY = event.originalEvent.pageY;
// execute drag logic with stored data
handleDrag();
});
// drag logic
function handleDrag() {
// new position along x axis
var currX = $(dragDetails.target).position().left;
var moveX = (dragDetails.desMouseX - dragDetails.orgMouseX);
$(dragDetails.target).css (
"left", ((parseInt(currX) + parseInt(moveX)) + "px")
);
// new position along y axis
var currY = $(dragDetails.target).position().top;
var moveY = (dragDetails.desMouseY - dragDetails.orgMouseY);
$(dragDetails.target).css (
"top", ((parseInt(currY) + parseInt(moveY)) + "px")
);
}