2
votes

I've got a jQuery UI sortable list that's connected with a draggable list. You can drag items out of the draggable list and drop them on the sortable list. This works great.

However, I want to intercept the drop and completely alter--replace, really--the list item that actually gets inserted into the sortable list. Looking at the "update" event for jQuery UI sortable, I see various ways to inspect the item that is being dropped, but I can't figure out how to say "don't insert the item that just got dropped--insert this item instead."

Is there a way to do that? If not, what is the "best practice" for handling this use case? I'm sure I'm not the first person to want to do something like this.

2

2 Answers

3
votes

There may be a better solution, but this might work for your situation:

$("#sortable").sortable({
    update: function (e, ui) {
        var myElement = $("<li style='background-color: red'>" + $(ui.item).text() + "</li>");

        $(ui.item).replaceWith(myElement);
    }
});

See demo: http://jsfiddle.net/lhoeppner/Qt6Qw/

The update event is called after the element was inserted, so if you really need to prevent that from happening, you probably need to intercept the beforeStop event. You can, for example prevent inserting like this:

$("#sortable").sortable({
    beforeStop: function () {
        $(this).sortable('cancel');
    }
});

However in that case, the original element just reverts and you'd have to remove it and manually figure out where it would have inserted.

0
votes

I am doing the same thing and the best solution I found was to use the stop event. I had tried the receive and update events earlier but the results were not favourable.

The only disadvantage with the stop event is it gets fired even if the items are sorted among themselves.