How to access the id of draggable element which is dropped into sortable

Nikolai picture Nikolai · Mar 19, 2009 · Viewed 28.8k times · Source

I am using the JQuery libs to implement drag and drop.

How do I get at the element that is being dragged when it is dropped into sortable list?

I want to get the id of the div being dragged. The following element is dragged:

<div class="control" id="control[1]" >
  <img src="img/controls/textfield.png" />
</div>

I have the standard dragging function from their example

$(".control").draggable({
  connectToSortable: '#sortable',
  helper: 'clone'
});

function stop in dragging section with next code return proper value

stop: function(event, ui) {
  alert(ui.helper.attr('id'));
}

And this is sortable element:

<ul id="sortable"><li>test</li></ul>

and his function:

$("#sortable").sortable({
  revert: true,
  accept: '.control',
  receive: function(event, ui) { 
    // here i need to get draggable element id
  }
});

I have tried various ui.id etc which doesn't seem to work.

receive: function(event, ui) { 
  $(ui.draggable).attr("id")
}

throws undefined.


Update:

Sorry, my fault :) As my mother used to tell - "Read API before coding". ui.item.attr('id') works fine.

Answer

Steerpike picture Steerpike · Mar 19, 2009

Try

receive: function(event, ui) { 
  $(ui.item).attr("id")
}

According to the documentation the receive (indeed all callbacks for sortable) get two arguments. The second argument should contain:

  • ui.helper - the current helper element (most often a clone of the item)
  • ui.position - current position of the helper
  • ui.offset - current absolute position of the helper
  • ui.item - the current dragged element
  • ui.placeholder - the placeholder (if you defined one)
  • ui.sender - the sortable where the item comes from (only exists if you move from one connected list to another)