Qrzysio
Qrzysio

Reputation: 1172

Sortable with dynamic content

So I use jQuery UI sortable plugin to sort photos in a small gallery.

$(function() {
  $("#area").sortable({
    items: '.sort-wrapper',
    cursor: "move",
    handle: ".photo-handler",
    opacity: 0.5,
    scroll: true,
    scrollSensitivity: 100,
    scrollSpeed: 5,
    revert: 100,
    tolerance: "pointer",
    update : function () {
      var order = $('#area').sortable('serialize');
      $.ajax({
      type : 'POST',
      url : '/file.php',
      data : order
    });
  }
}).disableSelection();

On the same page I dynamically add and remove photos. PHP script returns HTML code with div's with image links and buttons "remove" and "move" (sortable handler).

Example:

<div class="sort-wrapper">
  <a href="photo001.jpg"><img src="photo001m.jpg" alt=""></a>
  <button type="button" class="remove-this-photo">Remove</button>
  <button type="button" class="photo-handler">Move</button>
</div>

The problem is sortable stops working when I add new files or remove a file(s) from #area. I've been looking for solution, have found sortable('refresh') method, but it's not working for me.

The script which adds new photos in the #area is quite standard. I use $.ajax({}) and .done, .fail, .always methods. I managed to use sortable('destroy') method when starting uploading new files and do something like this after uploading is finished:

.always(function() {
  $("#area").sortable();
});

The code above makes the #area sortable again, but I must copy all the settings again to configure it my way. How to bind sortable to make it work after dynamic content is loaded or how to store all the settings outside sortable() and be able to use it again on the same page?

Upvotes: 0

Views: 1227

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you add new content to the sortable element you'll need to refresh the initialised instance. To do that, call the refresh option, like this:

.always(function() {
  $("#area").sortable('refresh');
});

Upvotes: 1

Related Questions