Skip to content

Instantly share code, notes, and snippets.

@marceloneil
Created August 11, 2016 21:20
Show Gist options
  • Save marceloneil/aff4c23fdb50de03b6ed6004614a3097 to your computer and use it in GitHub Desktop.
Save marceloneil/aff4c23fdb50de03b6ed6004614a3097 to your computer and use it in GitHub Desktop.
JQuery UI Draggable Table Swap
<table>
<tr>
<td class="droppable">
<div class="draggable">1</div>
</td>
<td class="droppable">
</td>
<td class="droppable">
<div class="draggable">2</div>
</td>
</tr>
<tr>
<td class="droppable">
</td>
<td class="droppable">
<div class="draggable">3</div>
</td>
<td class="droppable">
</td>
</tr>
<tr>
<td class="droppable">
<div class="draggable">4</div>
</td>
<td class="droppable">
<div class="draggable">5</div>
</td>
<td class="droppable">
<div class="draggable">6</div>
</td>
</tr>
</table>
var dragLastPlace;
var movedLastPlace;
$('.draggable').draggable({
placeholder: 'placeholder',
zIndex: 1000,
containment: 'table',
helper: function(evt) {
var that = $(this).clone().get(0);
$(this).hide();
return that;
},
start: function(evt, ui) {
dragLastPlace = $(this).parent();
},
cursorAt: {
top: 20,
left: 20
}
});
$('.droppable').droppable({
hoverClass: 'placeholder',
drop: function(evt, ui) {
var draggable = ui.draggable;
var droppable = this;
if ($(droppable).children('.draggable:visible:not(.ui-draggable-dragging)').length > 0) {
$(droppable).children('.draggable:visible:not(.ui-draggable-dragging)').detach().prependTo(dragLastPlace);
}
$(draggable).detach().css({
top: 0,
left: 0
}).prependTo($(droppable)).show();
movedLastPlace = undefined;
},
over: function(evt, ui) {
var draggable = ui.draggable;
var droppable = this;
if (movedLastPlace) {
$(dragLastPlace).children().not(draggable).detach().prependTo(movedLastPlace);
}
if ($(droppable).children('.draggable:visible:not(.ui-draggable-dragging)').length > 0) {
$(droppable).children('.draggable:visible').detach().prependTo(dragLastPlace);
movedLastPlace = $(droppable);
}
}
})
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
.droppable {
width: 100px;
height: 100px;
background: grey;
font-size: 15pt;
font-family: Helvetical, Arial, sans-serif;
color: white;
line-height: 100px;
vertical-align: middle;
text-align: center;
}
.draggable {
width: 100px;
height: 100px;
background: green;
}
.placeholder {
background: red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment