Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how to update draggable clone id?

I want to add draggable items to a sortable list, which works fine in my example on http://jsbin.com/ipese5/35

Problem is that I want to update id of the cloned item when dragged to the sortable list. Strange thing is that the following code updates the id to "new-id" in de ui object (as I can see in my console), but the id is not changed on the actual page html. Anyone has a solution?

$( "#init .block" ).draggable({
  helper: "clone",
  connectToSortable: ".list"
});

$(".list").sortable({
  connectWith: ".list",
  receive: function(event, ui) {
    $(ui.helper).attr("id","new-id");
    console.log(ui); 

    // surprisingly the next line works fine, but is not neccesary
    // $(ui.item).attr("id","new-id");
  }
});

<div id="init">
  <div id="new" class="block">Drag me</div>
  <div id="new" class="block">Drag me</div>
  <div id="new" class="block">Drag me</div>
</div>

<div class="list">
  <div class="block">Sort me</div>
  <div class="block">Sort me</div>
</div>
like image 517
Huub Avatar asked Apr 26 '11 09:04

Huub


1 Answers

In the receive event, you cannot access the actual item that is being created in the sortable list. Helper points to a clone that is used just for the dragging, item is the original item that you clicked on to drag.

But, the beforeStop event fires just before the receive event. In beforeStop, the item is actually the item being added to the list. So, in beforeStop you can save the item and then use it in receive.

Demo here: http://jsfiddle.net/kcg29/

var newItem;

$(".list").sortable({
  connectWith: ".list",
  beforeStop: function (event, ui) { 
      newItem = ui.item;
  },
  receive: function(event,ui) {
      $(newItem).doSomething();
  }
});​
like image 96
James Montagne Avatar answered Sep 18 '22 01:09

James Montagne