JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test">Drag Me!</div>
<div id="test2">Drag2 Me!</div>
CSS
div {
width: 100px;
height: 100px;
background: blue;
top:100px;
left:200px;
position: absolute;
color: white;
font: bold 18px/100px arial, sans-serif;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
JavaScript
function setDragOfElementOnAnother($draggableElement, $draggedElememnt, allowDragPredicate) {
var stopDragFunction = function () {
$draggedElememnt.data("drag", false);
$draggedElememnt.removeData("startPoint");
$("html, body").unbind("mouseup.drag");
$("html, body").unbind("mousemove.drag");
};
var dragFunction = function (e) {
if (!parseBoolean($draggedElememnt.data("drag"))) return;
var begin = $draggedElememnt.data("startPoint");
var newLeft = e.clientX - begin.x,
newTop = e.clientY - begin.y;
// Here you can add validations like:
// newLeft = Math.max(0, newLeft);
$draggedElememnt.css({
left: newLeft,
top: newTop
});
};
var startDragFunction = function (e) {
if ((e.clientX - $(this).offset().left < 0 || $(this).offset().left + $(this).width() < e.clientX) || e.clientY - $(this).offset().top < 0) return;
if (allowDragPredicate && !allowDragPredicate(e)) return;
$draggedElememnt.data("drag", true);
$draggedElememnt.data("startPoint", {
x: e.clientX - $(this).offset().left,
y: e.clientY - $(this).offset().top
});
$("html, body").bind("mouseup.drag", stopDragFunction);
$("html, body").bind("mousemove.drag", dragFunction);
};
$draggableElement.mousedown(startDragFunction);
$draggableElement.mousemove(dragFunction);
$draggableElement.mouseup(stopDragFunction);
}
function parseBoolean(str) {
if (str === true) return true;
if (str) return (/^true$/i).test(str);
return false;
}
setDragOfElementOnAnother($("#test"), $("#test"));
setDragOfElementOnAnother($("#test2"), $("#test2"));