Travis Travis - 1 year ago 173
jQuery Question

Enable draggable and droppable on dynamically created elements jQuery

I want to automatically enable 'draggable' and 'droppable' on dynamically created elements. I DON'T want to just reinitialize it after I add the element to the DOM.

For example:

$('static_element_such_as_body').on('event', 'dynamicElement', function(){

That is a truely dynamic event handler. How can I impliment the 'draggable' and 'droppable' to the .on or .live binder?

There is the code I'm using for drag and droppable:

helper: function() { //helper function is used to duplicate the event dragged

return $('<p>winning</p>').append($(this).find('.name').clone()); //Idk what class or where .name is but without it, it bombs out
stack: ".draggable", //this changes our z index to be the upper most
start: function(event, ui) { //this fires on start = this; //set up our c cariable
c.helper = ui.helper;
}).droppable({ //this let's us know this element is droppable
drop: function(event, ui) { //when you actually drop
over: function (event, ui) { //called when we are hovering over a droppable element with this selector
out: function(event, ui){

Answer Source

Apparently no one knows so I figured out a more 'automated' solution. Instead of manually re-initializing it once you add the element, you can use this event handler to automate that re-initializing for you.

$mainContainer.on('DOMNodeInserted', function(e){
    if($.inArray('relatable', != -1){

Where $mainContainer is a static element, such as $('body'), and 'relatable' is the name of the class that I use to know this element should allow drag and droppable. It's the class I use to initialize ie: $('.relatable').draggable()

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