Drop() gets called twice with Sortable/Droppable

2.5k views Asked by At

I have this code right here. I have two problems though:

  1. In the receive function, how can we get the element that just got dropped into the sortable? Not the one that was used to drop a new one, but the actual one that got dropped into the list?
  2. Since I couldn't find that, I decided to use the drop() function, but now, why is that function getting called twice?! I don't want that!

    $( "#sortable" ).droppable({
    
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function( event, ui ) {
            $(ui.draggable).editable(function(value, settings) { 
                 return(value);
                 },{
                 tooltip     : "Click to edit"
              });
        }
    }).sortable({
    
        revert: true,
        receive: function(event, ui) {
            $(this).children("li").each(function(index) {
                $(this).attr("id", "content-" + index);
                });
        }
    
    });
    
1

There are 1 answers

0
Mark Schultheiss On BEST ANSWER

I was curious, so I did a bit of playing around with this.

I did not see the 'receive' event fire at all in my testing with a droppable in play. Given that, I looked at your code, and it seems you want to set the id on the newly dropped. So, I did put together this: http://jsfiddle.net/ER5Jd/ - use that to see it in action adding the ID and listing the last list items id.
Sort and it shows the new last one in the list after the sort. My hope is that it helps you. Note: ui.helper in the "drop" is the helper item that is dragging around the screen (draggable clone set) but the actual clone is from the draggable.

my markup:

<ul id='firstOne'>First
    <li class='listItem'>oneF</li>
    <li class='listItem'>twoF</li>
</ul>
<ul id='secondOne'>Second<span></span>
    <li class='listItem'>oneS</li>
    <li class='listItem'>twoS</li>
</ul>

my code:

$('#firstOne .listItem').draggable({
    helper: 'clone'
});
giveId($('#secondOne'));// initial ids set

$("#secondOne").droppable({
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {
        $(ui.draggable).clone().css('background-color', 'pink')
          .attr('id', 'content-' + ($(this).find('.listItem').length + 1))
          .appendTo(this).siblings().css('background-color', 'yellow');
        showId($(event.target));
    },
    accept: '#firstOne .listItem'
}).sortable({
    revert: true,
    update: function(event, ui) {
        showId($(event.target));
    },
    receive: function(event, ui) {
        alert('receipt');
    }
});

function giveId(list) {
    list.find(".listItem").each(function(index) {
        $(this).attr("id", "content-" + index);
    });
    showId(list)
}
// show the last items id
function showId(list) {
    list.find('span').text(list.find('.listItem:last').attr('id'));
}