jQuery UI sortable with Ajax

jquery-ui-sortable.png

I just finished a session of intense jQuery hacking and here are some notes with regards to an interface making use of jQuery UI.

<ul id="listitems">
   <li class="list-item" id="item-1">
    <div class="item-mover"/>
    <div class="list-title">
     <span>Title1</span>
    </div>
   </li>
   <li class="list-item" id="item-2">
    <div class="item-mover"/>
    <div class="list-title">
     <span>Title2</span>
    </div>
   </li>
   <li class="list-item" id="item-3">
    <div class="item-mover"/>
    <div class="list-title">
     <span>Title3</span>
    </div>
   </li>
  </ul>

The above is the HTML shown in the picture. We will work with the listitems UL and use item-mover (the up and down arrows) as the dragger (more on that below).

function pl(class, method, pobj, func, url){
  pobj.class = class;
  pobj.method = method;
  $.post(url, pobj, func);
}

function plExec(class, method, pobj, func){
  pl(class, method, pobj, func, "/ajax/exec");
}

function getId(el){
  if(el.attr)
    return el.attr("id").split("-").pop();
  return 0;
}

.
.
.

$("#listitems").sortable({
  handle: ".item-mover",
  update: function(event, ui){
    var nxt_id = getId(ui.item.next());
    plExec("ItemList", "moveTo!", {id1: getId(ui.item), id2: nxt_id, id: 1});
  }
});

$("#listitems").disableSelection();

.
.
.

The handle: “.item-mover” takes part of me wanting to use only the up/down arrow icons as the legal dragger.

The update: … part is happening when the sorting/dragging stops, we then check which item we dragged and the immediately following item and send their numerical ids to the database, all this is possible because of the item property of the ui object that refers to the dragged item.

The ids will be used to re-save the ordering of the list. As you might or might not know it’s possible to easily send an array by way of draggable’s toArray or serialize but I wanted to avoid that as it would eat up unnecessary bandwidth as the list in question could potentially become very long.

I also wanted to save the ordering on each drag, ie not have a save button that would send the whole state. It’s a question of having an intuitive GUI and in this case I think we’ve solved it pretty nicely by sending as little information as possible considering that the updates could become rather frequent.


Related Posts

Tags: , , ,