JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
<div id="box-1" class="box">Box 1</div>
<div id="box-2" class="box">Box 2</div>
<div id="box-3" class="box">Box 3</div>
</div>
CSS
.box {
background:red;
width:50px;
height:50px;
border:black 1px solid;
position:absolute;
}
#box-2 {
left:35px;
top:35px;
/* NOT aligned with grid */
}
#box-3 {
left:65px;
top:65px;
/* NOT aligned with grid */
}
#container {
border:solid blue 1px;
width:100%;
height:200px;
position:absolute;
background:whitesmoke url('https://s3.amazonaws.com/com.appgrinders.test/images/grid_20.png') repeat;
}
JavaScript
$('#box-1').draggable({
grid: [20, 20]
});
$('#box-2').draggable({
grid: [20, 20]
});
var isDraggable = false;
$('#box-3').mousedown(function (e) {
console.log('MOUSE DOWN');
if (!isDraggable) {
var $this = $(this);
// Reposition to nearest grid position:
currentX = parseInt($this.css('left'));
currentY = parseInt($this.css('top'));
nearestGridX = Math.round(currentX / 20) * 20;
nearestGridY = Math.round(currentY / 20) * 20;
$this.css({
left: nearestGridX + 'px',
top: nearestGridY + 'px'
});
// Turn yellow:
$this.css({
background: 'yellow'
});
// Make draggable:
isDraggable = true;
$this.draggable({
grid: [20, 20],
start: function (event, ui) {
console.log('START');
}
});
$(this).trigger(e);
}
});