Kesong Xie Kesong Xie - 5 months ago 42
jQuery Question

How to use delegate for UI draggable?

I have to add draggable and droppable for those new elements inserted on the page, but since they are not yet inherited the draggable and droppable like those that are done during the page loaded, I have to manually add draggable and droppable for those newly created elements.

For click events, I could simply do this

$('body').on({
click:function(){
//codes here
}

},'#element');


but this doesn't seem to work when I deal with draggable and droppable

I have my draggable set up like this

$('.photo-segment').draggable({
containment:'#layout-draggable',
axis:'y',
scroll:false,
revert:"invalid",
drag:function(event,ui){
$(this).css({'z-index':9999, 'opacity':'0.8'});
},
stop:function(event,ui){
$(this).css({'z-index':'', 'opacity':'1'});
}
});


and I droppable set up like this

$('.photo-segment-container').droppable({
accept:'.photo-segment',
tolerance:'intersect',
over:function(event, ui){
//codes here
},
drop:function(event, ui){
//codes here
},
deactivate:function(event,ui){
return false;
}

});


I could have manually run this whole bunch of codes above right after I created those elements, I have done something like this

$('.photo-segment').draggable();
$('.photo-segment-container').droppable();


but in this case, I can't retrieve all those setups. Do I have to run my initial set up again?

Answer

Yes, you will need to initialize draggable/droppable again for the newly added elements.

You could save your settings in a separate objects to not repeat the code.

var dragSettings = {...};
...
$('.photo-segment').draggable(dragSettings);