JSFiddle - React, Tailwind, and code Playground
by yelton
HTML
<div class="parent">
<div class="drag">Drag me</div>
<div class="drag2">Drag me 2</div>
</div>
CSS
.parent {
width:500px;
height:400px;
background:yellow
}
.drag {
background:#eee;
width:100px;
height:100px;
border:1px solid #ccc;
z-index:1;
}
.drag2 {
background:#069;
width:100px;
height:100px;
border:1px solid #ccc;
z-index:1;
}
JavaScript
$.fn.draggable = function (opt) {
opt = $.extend({
handle: "",
cursor: "move",
axis: null,
containParent: false
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function (e) {
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
var parW = $($el).parents().outerWidth(),
parH = $($el).parents().outerHeight();
// console.log($drag.offset().top + ", " + pos_y);
$drag.css('z-index', 1000).parents().on("mousemove", function (e) {
var off_top = e.pageY + pos_y - drg_h,
off_left = e.pageX + pos_x - drg_w,
offst = null;
if (opt.containParent === true) {
if (off_left < 0) off_left = 0;
if (off_left > parW - drg_w) off_left = parW - drg_w;
if (off_top < 0) off_top = 0;
if (off_top > parH - drg_h) off_top = parH - drg_h;
}
if (opt.axis == "x") {
offst = {
left: off_left
};
} else if (opt.axis == "y") {
offst = {
top: off_top
};
} else {
offst = {
left: off_left,
top: off_top
};
}
$('.draggable').offset(offst).on("mouseup", function () {
$drag.parents().off('mousemove');
...