Search code examples
jqueryajaxjquery-uijquery-jscrollpane

Sortable List Populated With Dynamic Data


I am having a bit of a problem getting JQuery-UI interactions working on a page of mine. I haven't used JQuery-UI before, so I started out by trying the sortable interaction with the hopes of making it drag-and-drop and sortable later on. However, I've been banging my head against the wall and been unable to even get the sortable working.

The content I am trying to sort is being loaded dynamically with ajax. Here is a representation of what the content looks like:

<ul id="category_list">
    <li class="category" data-category-id="17">Education</li>
    <li class="category" data-category-id="20">General Information</li>
    <li class="category" data-category-id="14">Music / Movies / Television</li>
    <li class="category" data-category-id="18">Navigation</li>
    <li class="category" data-category-id="19">Retailers</li>
    <li class="category" data-category-id="16">Social Media</li>
    <li class="category" data-category-id="15">Web Results</li>
</ul>

This JQuery function loads the data:

// load all the engines in a category
$('#container').on("click", ".buttonclass", function() {
    $.get("/categories", {
      id : $(this).attr('data-id')
      }, function(data) {
          var pane = $("#categories").data('jsp');
          pane.getContentPane().html(data);
          pane.reinitialise();
      });
});

(the pane-related stuff is because this is scrollable by a JScrollPane). I try adding code to this function above to make the list elements sortable, but nothing works. Some things I've tried are:

$('.category').sortable();
...
$('.category'.each(function(){$(this).sortable()};
...
$("#category_list").sortable();
...
$('.category').sortable('refresh');
...
$('.category'.each(function(){$(this).sortable('refresh')};
...
$("#category_list").sortable('refresh');

I tried adding the code to on click handler both inside the callback function (of the $.get) and after it with no luck.

Static data hard-coded in the page (inside the JscrollPane) has no problems sorting. Just the dynamic content is causing trouble.

Any help would be greatly appreciated.


Solution

  • Figured out the problem and it was the JScrollPane. Although the JScrollpane has no problems with static data and sortable/draggable/droppable it seems to cause problems when dynamically populating it.

    Removed the JScrollPanes and all if fine using:

    $("#category_list").sortable();