I'm having a problem with applying jQueryUI droppable to a dynamically created div.
$(".item").draggable({ helper: 'clone'});
$(".box").draggable({containment : '#area'});
$(".box").droppable({
drop: function(event, ui) {
if ($(ui.draggable).hasClass("area")){
// call another function
}else{
$(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
$('.area').draggable();
}
}
});
An .item is supposed to drop in .box. It works well until I call the second function (by clicking a button):
function add_box(){
$("<div class='box'></div>").prependTo( "#area" );
$(".box").droppable(); // i tried this (didn't work).
$(".box").draggable(); // should be draggable as well
}
When you're calling $(".box").droppable(); in add_box function, you're reapplying droppable to all .box items, but without the options, so you're losing your expected behavior.
You should apply it only to the newly created element, and you need to define your options as well. You could do something like this for example:
// define your options as an object
var droppableOptions = {
drop: function(event, ui) {
if ($(ui.draggable).hasClass("area")){
// call another function
} else {
$(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
$('.area').draggable();
}
}
}
function add_box(){
var newBox = $("<div class='box'></div>").prependTo( "#area" );
// you apply droppable to your new box, with the options you need
newBox.droppable(droppableOptions);
newBox.draggable(); // should be draggable as well
}
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