jQuery UI draggable element dropped into sortable

David Hellsing picture David Hellsing · Sep 27, 2012 · Viewed 8.9k times · Source

I have a list of draggable items, and I wish to be able to drag them onto a sortable content block. Here’s my markup:

<div class='items'>
    <div class="one">One</div>
    <div class="two">Two</div>
</div>

<div class="content">
    <div class="block">Foo</div>
    <div class="block">Bar</div>
</div>

The thing is, that I want the dragged item to "become" a block as soon as the dragging starts and remain a block when it’s dropped. I have tried this:

$('.items div').draggable({
    helper: function(e) {
        return $('<div>').addClass('block').text( $(e.target).text() );
    },
    connectToSortable: ".content"
});

$('.content').sortable();​

Fiddle: http://jsfiddle.net/MF4qu/

But even if I create a custom helper that looks like a block, it reverts back to the original dragged element as soon as it’s dropped. Does anyone know how to properly insert a block in my example page? I already looked through the UI API but I can’t figure it out.

Answer

Andrew picture Andrew · Sep 27, 2012

When the draggable element is dropped into sortable, it triggers the sortable update event. One solution is to listen to that event, and turn the dropped item into a block:

$('.items div').draggable({
    helper: function(e) {
        return $('<div>').addClass('block').text( $(e.target).text() );
    },
    connectToSortable: ".content"
});

$('.content').sortable({
    update: function (event, ui) {
        ui.item.addClass('block');
    }
});​

Working demo: http://jsfiddle.net/DaXuT/1/