EasyBakeOven EasyBakeOven - 3 years ago 170
HTML Question

jQuery UI - append a class, make it draggable

Hello!

I just started with jQuery UI, so I'm already stuck with something...

I'm trying to make a web program which allows the user to make a floor plan. It has a drag & drop function.




It has a menu with several items which can be dragged around. The problem is, when it's dragged around, the item in the menu disappears (because it's dragged around). So I tried to fix that using this code:

jQuery:

$('.notActive').draggable({ //.notActive is an item in the menu
stop: function(){
$(this).removeClass('notActive');
$(this).addClass('active'); //make it an active item
$('#menu').append($('<div class="item notActive">Furniture</div>'));
//this creates a new item in the menu
}
});


Each
item
has the class
.notActive
because it's not dragged. When it's being dragged by the user it removes that class and receives the class
.active
. So when it's dragged it creates a new element inside
#menu
with the class
.notActive
. The problem is, that the new created (appended(?)) item in the menu is not
.draggable()
, even though it has the class
.notActive
.

Why is this? How can I create a new instance that IS
.draggable()
?

Apologies for any grammar mistakes, I'm Dutch.

EDIT

Here's the Fiddle: https://jsfiddle.net/8tpy7x3e/

Answer Source

You're not explicitly calling draggable on the new item that's added to the menu.

Something like this would work:

$('.notActive').draggable({ //.notActive is an item in the menu
  stop: function(){
    $(this).removeClass('notActive'); 
    $(this).addClass('active'); //make it an active item
    //Create a new object
    var newItem = $('<div class="item notActive">Furniture</div>');
    //Make the new item "draggable" and add it to the menu
    newItem.draggable();
    $('#menu').append(newItem);
    //this creates a new item in the menu
  }
});

Fiddle example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download