Swapping two jQuery draggable list items not working properly (with jsFiddle example)
Posted
by
Tony_Henrich
on Stack Overflow
See other posts from Stack Overflow
or by Tony_Henrich
Published on 2011-01-03T20:48:21Z
Indexed on
2011/01/03
20:54 UTC
Read the original article
Hit count: 244
The minimalist working example below swaps the two boxes when box 'one' is dragged and dropped on box 'two'. The problem is that when box 'one' is dropped, its style has 'top' & 'left' values causing it to be placed away from where it should drop. Its class includes 'ui-draggable-dragging'. It seems the top & left values are related to the amount the elements were dragged before the drop. And the dragging was 'interrupted' hence the residual 'ui-draggable-dragging' class?
What am I missing to make the swap work seamlessly? full jsfiddle example here
<html>
<head>
<script type="text/javascript" src="includes/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="includes/jquery-ui-1.8.2.custom.min.js"></script>
<script type="text/javascript">
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
$(document).ready(function() {
options = {revert: true};
$("li").draggable(options)
$('#wrapper').droppable({
drop: function(event, ui) {
$(ui.draggable).swapWith($('#two'));
}
});
});
</script>
</head>
<body>
<form>
<ul id="wrapper">
<li id='one'>
<div style="width: 100px; height: 100px; border: 1px solid green">
one<br /></div>
</li>
<li id='two'>
<div style="width: 110px; height: 110px; border: 1px solid red">
two<br /></div>
</li>
</ul>
<br />
</form>
</body>
</html>
© Stack Overflow or respective owner