tags:

views:

19

answers:

1

Hi,

I have a sortable list. When a new item is dropped into the list (from a draggable), I'd like to get access to it to perform some operations on it. This is what I have:

$("#mySortableList").sortable({
    receive: function(event, ui) {
        alert("this is the dropped item: " + ui.item.toString());
    }
}).disableSelection();

so "ui.item" is the element that was dropped, but it's not the duplicated item that will now be part of my list. How do I get access to the new item that was dropped? I am using the exact demo from the jquery-ui site here: http://jqueryui.com/demos/draggable/#sortable

Thanks

A: 

You can get the item in the stop event and check that it came from the draggable (it doesn't have a handle attached, which it would if it was from the sortable), like this:

$("#mySortableList").sortable({
    stop: function(event, ui) {
    //check it wasn't here previously
    if(!ui.item.data('tag') && !ui.item.data('handle')) {
        ui.item.data('tag', true); //tag new draggable drops
        alert("this is the dropped item: " + ui.item.toString());
    }
}).disableSelection();

You can see a demo to play/test with here, since a handle doesn't get added, at least not in a way that matters, we're tagging items dropped from the draggable so that they won't fire the alert again when moved inside the sortable.

Nick Craver
Wow that's great! Is there a way to also get access to the dragged item within the stop() event? Looks like you can get one or the other, but not both, for example [receive => dragged item], [stop => cloned item]. I basically need to transfer some data from the dragged to the cloned item. This was a great start, thank you. In the worst case, I guess I can set a pointer to the dragged item in receive(), since it is called first, then use it in stop().