I'm trying to write a helper
function for jQueryUI to set an attribute on an item being dragged from a 'draggable' list to a 'sortable' list. (The reason I need to do this is that the latest version of jQueryUI deletes the 'id' attribute of dropped items)
However the attribute is not making it to the 'sortable' list. Am I doing something wrong in the helper function?
$("#draggable > li").draggable({
connectToSortable: "#sortable",
helper: function (event) {
var id = $(this).attr('id');
var ret = $(this).clone();
ret.attr('dragId', id);
console.log('dragId: ', ret.attr('dragId'));
return ret();
}
});
$( "#sortable" ).sortable({
start: function( event, ui ) {
console.log( "sortable start: dragId=", ui.item.attr( "dragId" ) );
},
stop: function( event, ui ) {
console.log( "sortable stop: dragId=", ui.item.attr( "dragId" ) );
}
});
When I drag an item from the draggable list to the sortable list, it prints in the console:
dragId: itemA
sortable start: dragId= undefined
sortable stop: dragId= undefined
I would expect it to print:
dragId: itemA
sortable start: dragId= itemA
sortable stop: dragId= itemA
Here is the full example (with HTML) on JsBin
You're setting the dragId
attribute on the helper element, so you should use ui.helper
instead of ui.item
:
console.log("sortable start: dragId=", ui.helper.attr("dragId"));
EDIT: Nicola Peluchetti is right in his comment below: ui.helper
will indeed be null
during the stop
event. Since you probably want to use the dragId
attribute during that event, a workaround would be to copy the attribute during the start
event, when both ui.helper
and ui.item
are available:
$("#sortable").sortable({
start: function(event, ui) {
ui.item.attr("dragId", ui.helper.attr("dragId"));
console.log("sortable start: dragId=", ui.item.attr("dragId"));
},
stop: function(event, ui) {
console.log("sortable stop: dragId=", ui.item.attr("dragId"));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With