JSFiddle - React, Tailwind, and code Playground
HTML
<button id="on">Drag On</button>
<button id="off">Drag Off</button>
<div id="mydiv"></div>
CSS
#mydiv {
height: 50px;
width: 50px;
background: #000;
}
JavaScript
$.fn.extend({
cannotDragMe: function () {
return this.each(function () {
var $this = $(this);
$this = $(this);
return $this.css('cursor', 'default').off("mousedown.drag").off("mousemove.drag").off("mouseup.drag");
});
},
canDragMe: function (opt) {
opt = $.extend({
handle: "",
cursor: "move"
}, opt);
var $el;
if (opt.handle === "") {
$el = this;
} else {
$el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown.drag", function (e) {
var $drag;
if (opt.handle === "") {
$drag = $(this).addClass('draggable');
} else {
$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;
$drag.css('z-index', 1000).parents().on("mousemove.drag", function (e) {
$('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup.drag", function () {
$(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup.drag", function () {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
});
$('#on').click(function () {
$('#mydiv').canDragMe();
});
$('#off').click(function () {
$('#mydiv').cannotDragMe();
});