Search code examples
jqueryjquery-uijquery-ui-draggablejquery-ui-droppable

Prevent clone floating back when swapping items with jQuery UI


I am using jQuery draggable/droppable to enable elements in a grid to be swapped. For example, when element 1 is dropped onto element 2 they change places.

There are two problems:

  1. After a successful drag-drop the clone still floats back to its original position. How can I prevent this? I only want it to float back if it's not dropped onto a valid target.

  2. Ideally I'd like to set helper: original as well, but when I tried this I couldn't work out how to correctly calculate the swapped positions in the drop function.

I've put the code on jsFiddle, and below for reference:

<div id="room"></div>

<script>
$(function() {
//Set up seats - four rows of eight
for (var row = 0; row < 4; row++) {
    for (var col = 0; col < 8; col++) {
        $('#room').append('<div class="seat" style="top: ' + (row * 45 + 15) + 'px; left: ' + (col * 117 + 18) + 'px;">' + (row * 4 + col + 1) + '</div>');
    }
}

//Swap function from http://blog.pengoworks.com/index.cfm/2008/9/24/A-quick-and-dirty-swap-method-for-jQuery
jQuery.fn.swap = function(b) {
    b = jQuery(b)[0];
    var a = this[0];
    var t = a.parentNode.insertBefore(document.createTextNode(''), a);
    b.parentNode.insertBefore(a, b);
    t.parentNode.insertBefore(b, t);
    t.parentNode.removeChild(t);
    return this;
};

$(".seat").draggable({
    revert: true,
    helper: "clone"
});

$(".seat").droppable({
    accept: ".seat",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {

        var draggable = ui.draggable,
            droppable = $(this),
            dragPos = draggable.position(),
            dropPos = droppable.position();

        draggable.css({
            left: dropPos.left + 'px',
            top: dropPos.top + 'px'
        });

        droppable.css({
            left: dragPos.left + 'px',
            top: dragPos.top + 'px'
        });
        draggable.swap(droppable);
    }
});

});
</script>

Solution

  • I resolved this with $(ui.helper).hide(); in the drop function.