JSFiddle - React, Tailwind, and code Playground
HTML
<div class="space"></div>
<div class="container">
<div class="draggable"></div>
</div>
CSS
html,
body { margin: 100px 100px; }
.space { height: 100px; }
.container {
width: 400px;
height: 400px;
background-color: #efefef;
}
.draggable {
top: 160px;
left: 160px;
width: 80px;
height: 80px;
background-color: #0088cc;
cursor: pointer;
border-radius: 40px;
}
JavaScript
$(function() {
window.mousedown = 0;
$(window).on('mousedown mouseup', function(e) {
if(e.type == 'mousedown') { this.mousedown++; }
else { this.mousedown--; }
});
var Draggable = function(dragItem, dragBoundary) {
this.item = $(dragItem).css('position', 'absolute');
this.item.on('mousemove', $.proxy(this.handleDragEvent, this));
this.boundary = $(dragBoundary).css('position', 'relative');
};
Draggable.prototype.handleDragEvent = function(e) {
if(window.mousedown) {
var mousePosition = this.mapToBoundary([e.clientX, e.clientY]);
this.mouseX = mousePosition[0],
this.mouseY = mousePosition[1];
if(typeof this.prevMouseX == "undefined") this.prevMouseX = this.mouseX;
if(typeof this.prevMouseY == "undefined") this.prevMouseY = this.mouseY;
this.itemX = this.item.offset().left - this.boundary.offset().left;
this.itemY = this.item.offset().top - this.boundary.offset().top;
var deltaX = this.mouseX - this.prevMouseX,
deltaY = this.mouseY - this.prevMouseY;
this.item.css({
'left': this.itemX + deltaX,
'top': this.itemY + deltaY
});
this.restrictItemToBoundary();
this.prevMouseX = this.mouseX;
this.prevMouseY = this.mouseY;
}
};
Draggable.prototype.mapToBoundary = function(coord) {
var x = coord[0] - this.boundary.offset().left;
var y = coord[1] - this.boundary.offset().top;
return [x,y];
};
Draggable.prototype.restrictItemToBoundary = function() {
var position = this.item.position();
position.right = position.left + this.item.outerWidth();
position.bottom = position.top + this.item.outerHeight();
if(position.left <= 0) {
...