10

I'm adding list items to a page dynamically with $.get, then appending them to the OL element. Pretty usual to this point.

But jQuery isn't aware of these new items when they get loaded into the page, and I'm not being able to make them sortable.

I made some trials with jQuery Live, but didn't get anywhere whit that...

4 Answers 4

18

The refresh method of .sortable() does not seem to recognize li's which are NOT added via the .sortable() functions.

Try adding your .sortable() initialisation code into a function which you call on document ready AND in you code where you dynamically add li's.

Instead of:

jQuery(document).ready(function() {
    jQuery("#mySortableOL").sortable({
        ...
    });
}
...
jQuery("#mySortableOL").append(...);
jQuery("#mySortableOL").sortable("refresh");

Try something like:

jQuery(document).ready(function() {
    jQuery("#mySortableOL").doSort();
}
...
jQuery("#mySortableOL").append(...);
doSort();
...
function doSort(){
    jQuery("#mySortableOL").sortable({
        ...
    });
}
2
  • 1
    It is not only the LI, it is basically everything, but the approach is correct and working. Jun 24, 2011 at 13:35
  • Exactly a correct answer. Thanks for saving my day! Jul 20, 2018 at 4:20
7

Did you try .sortable('refresh')? http://docs.jquery.com/UI/Sortable#method-refresh

1
  • 1
    Why is this not the accepted answer? This is by the far the cleanest way of managing this ajax issue.
    – Brad Bird
    Oct 21, 2015 at 11:18
0

on the tail end of your code just append .sortable({}); with all your parameters respecified. There's probably a way to do this without duplicating your code by using a function or something, but at least this works.

$('#List').live('click',function(e){

var myHTMLcode = '<li>New Item</li>'

myHTMLcode.appendTo('#List').sortable({
 items  : 'li',
 axis  : 'xy',    

 update  : function(event, ui){SPECIFIC Sortable FUNCTION CODE HERE}).fadeIn();
)};
-2

I found this solution and working fine for me.

makesortable = function(){
        $( "#mylist" ).sortable({
            ...
        })
      };
...
// after list refresh :
makesortable();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.