Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI draggable element dropped into sortable

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.

like image 581
David Hellsing Avatar asked Sep 27 '12 16:09

David Hellsing


1 Answers

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/

like image 164
Andrew Avatar answered Sep 22 '22 00:09

Andrew