Swap Draggables with Animation
http://stackoverflow.com/questions/13656611/how-to-swap-draggables-with-animation-using-jqueryui
by Ravindra Athreya
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swapping of tiles with Animation</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<style>
.droppable {
float: left;
margin-left: 100px;
width: 200px;
height: 50px;
border: 1px solid red;
padding: 5px;
}
.draggable {
width: 200px;
height: 50px;
background: green;
text-align: center;
line-height: 50px;
}
.ui-draggable-dragging {
background: blue;
}
.hoverClass {
border: 2px solid red;
}
</style>
</head>
<body>
<div class='droppable'>
<div class="draggable">Draggable 1</div>
</div>
<div class='droppable'>
<div class="draggable">Draggable 2</div>
</div>
<div class='droppable'>
<div class="draggable">Draggable 3</div>
</div>
</body>
</html>
JavaScript
$(document).ready(function () {
window.startPos = window.endPos = {};
makeDraggable();
$('.droppable').droppable({
hoverClass: 'hoverClass',
drop: function(event, ui) {
var $from = $(ui.draggable),
$fromParent = $from.parent(),
$to = $(this).children(),
$toParent = $(this);
window.endPos = $to.offset();
swap($from, $from.offset(), window.endPos, 200);
swap($to, window.endPos, window.startPos, 1000, function() {
$toParent.html($from.css({position: 'relative', left: '', top: '', 'z-index': ''}));
$fromParent.html($to.css({position: 'relative', left: '', top: '', 'z-index': ''}));
makeDraggable();
});
}
});
function makeDraggable() {
$('.draggable').draggable({
zIndex: 99999,
revert: 'invalid',
start: function(event, ui) {
window.startPos = $(this).offset();
}
});
}
function swap($el, fromPos, toPos, duration, callback) {
$el.css('position', 'absolute')
.css(fromPos)
.animate(toPos, duration, function() {
if (callback) callback();
});
}
});