I came across this problem trying to improve performance on manipulating huge lists of draggables; I tried removing a parent container so batch processing items would get faster (so each processing would not fire a DOM refresh) and re-inserting the container afterwards did cause the draggables to stop working. For example
<div id="listParent">
<div id="listWrapper">
<ul id="draggableList">
<li class="draggable">Item 1</li>
<li class="draggable">Item 2</li>
<li class="draggable">Item 3</li>
<li class="draggable">Item 4</li>
<li class="draggable">Item 5</li>
<!-- many more items here -->
</ul>
</div>
</div>
<script type="text/javascript">
$(function() {
$( ".draggable" ).draggable({
revert: true
});
function filterItems(text) {
var p = $('#listWrapper').remove();
// for each <LI> element, hide the ones who do not match `text`'s value
p.appendTo('#listParent');
}
// ...
});
</script>
So, invoking filterItems('foo');, for example, cause the items to not be draggables anymore. Do I have to re-apply draggable on the <LI> elements again? If so, then there is no point of removing the parent to speed up the process if I have to re-apply something afterward anyway, is it?
Use
.detach()instead of.remove()to preserve attached event handlers. Here’s an excerpt from the docs.Emphasis mine.
Here’s a fiddle.