JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.jsdelivr.net/interact.js/1.2.6/interact.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div>
<p id="position">
Position
</p>
</div>
<div class="container">
<div data-x="72" data-y="72" class="draggable ui-widget-content">
<p>Default (snap: true), snaps to all other draggable elements</p>
</div>
<div data-x="100" data-y="90" class="draggable ui-widget-content">
<p>Default (snap: true), snaps to all other draggable elements</p>
</div>
<div data-x="300" data-y="72" class="draggable ui-widget-content">
<p>Default (snap: true), snaps to all other draggable elements</p>
</div>
</div>
CSS
.draggable { position: absolute; width: 90px; height: 80px; padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em; }
.ui-widget-content p { margin: 0; }
.ui-widget-content {
border: 1px solid #aaaaaa;
background-color: #ffffff;
color: #222222;
}
.container
{
background-color: #FF0000;
position: relative;
width: 800px;
height: 900px;
}
JavaScript
var myItems = [];
//var pos = {x: 0, y: 0};
$('.draggable').each(function() {
$( this )[0].style.transform =
'translate(' + $( this )[0].getAttribute('data-x') + 'px, ' + $( this )[0].getAttribute('data-y') + 'px)';
var pos = {x: 0, y: 0};
pos.x = parseInt($( this )[0].getAttribute('data-x'));
pos.y = parseInt($( this )[0].getAttribute('data-y'));
console.log(pos);
myItems.push(pos);
});
console.log(myItems);
interact('.draggable')
.draggable({
onmove: dragMoveListener,
snap: {
//targets: myItems
},
onend: function (event) {
$('.draggable').each(function() {
var pos = {x: 0, y: 0};
pos.x = parseInt($( this )[0].getAttribute('data-x'));
pos.y = parseInt($( this )[0].getAttribute('data-y'));
console.log(pos);
myItems.push(pos);
});
}
});
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
$('#position').text('x: ' + parseFloat(target.getAttribute('data-x')) + ' - y: ' + parseFloat(target.getAttribute('data-y')));
var result = $.grep(myItems, function(e)
{
if(e.x == parseInt(target.getAttribute('data-x')) || e.y
== parseInt(target.getAttribute('data-y')))
return 1;
});
if (result.length >= 1)
target.style.backgroundColor = '#CCC';
else
target.style.backgroundColor='#FFF';
//myItems = [];
/*$('.draggable').each(function() {
pos.x = parseInt($(this)[0].getAttribute('data-x'));
pos.y =...