I’m working on a page that requires constant HTML elements to be added, removed and sorted from the DOM. I have a hidden DIV that contains all the blocks of code that I use clone() on and append it to the DOM. sortable() works on list-items already in the DOM, but not on DOM injected list-items after the DOM is done loading. I have the following list, simplified for example purpose:
<ul class="sprite-list">
<li>
<a href="#">
<img src="icon.png">
</a>
</li>
<li>
<a href="#">
<img src="icon.png">
</a>
</li>
<li class="sprite-add">
<a href="#">Add</a>
</li>
</ul>
I use the following jQuery code:
$('ul.sprite-list').sortable({
items: 'li:not(.sprite-add)',
containment: 'parent',
opacity: 0.7
}).disableSelection();
With that list hardcoded in the page, it works great. But after I cloned the same list into the DOM I can’t seem to drag & drop them.
I’ve read and seen working examples of sortable() working live. I also saw people recommend using .sortable(‘refresh’). So I tried
$('ul.sprite-list').sortable('refresh');
or
$.fn.sortable('refresh');
but all without success. What am I missing here?
edit: I noticed after injecting the cloned code, the list does have the class ui-sortable which all sortable lists get.
edit 2: I don’t know if it’s relevant but I use a seperate function to get the cloned elements:
function cloneElement(element){
var container = $('#sprite-clone');
if(element == 'generationContainer'){
return container.find('.sprite-generation-container').clone(true);
}
else if(element == 'groupContainer'){
return container.find('.sprite-group-container').clone(true);
}
else if(element == 'sprite'){
return container.find('>li:first').clone(true);
}
else if(element == 'customForm'){
return container.find('.customForm').clone(true);
}
}
Then when it’s needed I use var generationContainer = cloneElement(‘generationContainer’);
I’m not sure if that affects anything though.
Well the working examples code doesn’t clone, but add new content, so its a different thing.
Since I cannot see the rest of the code, then I’m only theorizing. Fix could be done by recalling sortable. So if you would put your sortable code inside a function, call it on document ready and then again when a element as been added.
Example: http://jsfiddle.net/BWkFp/
HTML
JS
Hope you get my point. This code works well for me 🙂