JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery.gridster/0.5.4/jquery.gridster.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.gridster/0.5.4/jquery.gridster.js"></script>
<h1>Swap elements between gridsters</h1>
<h2>From here</h2>
<div id="demo-1" class="gridster">
<ul>
<li data-row="1" data-col="1" data-sizex="1" data-sizey="1" class="gs-w">0</li>
<li data-row="1" data-col="2" data-sizex="1" data-sizey="1" class="gs-w">1</li>
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="gs-w">2</li>
</ul>
</div>
<h2>To here</h2>
<div id="demo-2" class="gridster">
<ul>
<li data-row="1" data-col="1" data-sizex="1" data-sizey="1" class="gs-w">0</li>
<li data-row="1" data-col="2" data-sizex="1" data-sizey="1" class="gs-w">1</li>
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="gs-w">2</li>
</ul>
</div>
CSS
.gridster * {
margin: 0;
padding: 0;
}
ul {
list-style:none;
}
li {
background: grey;
}
JavaScript
var gridster = [];
var startPosition = {};
$(function() {
gridster[0] = $("#demo-1 ul").gridster({
namespace: '#demo-1',
widget_base_dimensions: [100, 55],
widget_margins: [5, 5]
}).data('gridster');
gridster[1] = $("#demo-2 ul").gridster({
namespace: '#demo-2',
widget_base_dimensions: [100, 55],
widget_margins: [5, 5]
}).data('gridster');
$('.gridster li').on('mousedown', mouseDownHandler).on('mouseup', mouseUpHandler );
});
function mouseDownHandler(event)
{
event = event || window.event; // IE-ism
/** save start position to see if we dragged **/
startPosition = {
x: event.clientX,
y: event.clientY
};
}
function mouseUpHandler(event)
{
event = event || window.event; // IE-ism
/** get drop position to see if we dragged and where we dropped it **/
var dropPosition = {
x: event.clientX,
y: event.clientY
};
/** the element we clicked or dragged on **/
var liElement = $(this);
/** the gridster of the element we clicked on **/
var currentGridster = liElement.closest('.gridster');
/** the gridster object of the element we clicked on **/
var gridsterObject = getGridsterObjectById(currentGridster.attr('id'));
/** check if we dragged **/
if( startPosition.x == dropPosition.x && startPosition.y == dropPosition.y ) {
return true;
}
/** loop through all gridsters to check if we dropped the element in here **/
$('.gridster').each(function() {
var offset = $(this).offset();
/** check if element is dropped in the current gridster **/
if(
dropPosition.x > offset.left &&
dropPosition.x < ( offset.left+$(this).width() ) &&
dropPosition.y > offset.top &&
dropPosition.y < ( offset.top+$(this).height() ) &&
$(this).attr('id') != currentGridster.attr('id')
) {
...