Rich Buggy

...Developer, CTO, Entrepreneur

September, 2010

...now browsing by month

 

jQuery UI sortable

Thursday, September 2nd, 2010

Recently I’ve been playing with a list of lists using the jQuery UI sortable component. Graphically it looks something like:

  • List 1
    • Item 1
    • Item 2
    • Item 3
  • List 2
    • Item 5
    • Item 6
    • Item 7
  • List 3
    • Item 7
    • Item 8
    • Item 9

The HTML for this is pretty simple

<ul  class="lists">
    <li>
        <h1>List 1</h1>
        <ul id="list_1" class="list">
            <li id="item_1">Item 1</li>
            <li id="item_2">Item 2</li>
           <li id="item_3">Item 3</li>
        </ul>
    </li>
    <li>
        <h1>List 2</h1>
        <ul id="list_2" class="list">
            <li id="item_4">Item 4</li>
            <li id="item_5">Item 5</li>
            <li id="item_6">Item 6</li>
        </ul>
    </li>
    <li>
        <h1>List 3</h1>
        <ul id="list_3" class="list">
            <li id="item_7">Item 7</li>
            <li id="item_8">Item 8</li>
            <li id="item_9">Item 9</li>
        </ul>
    </li>
</ul>

I want the user to be able to re-order the lists, the items in each list and move items from one list to another. 18 lines of Javascript later I had it handling this perfectly and displaying alerts telling me where items were moved to, the list they were in and if the lists were re-ordered.

$(function() {
    $(".lists").sortable({
        forcePlaceholderSized: true,
        stop: function(event, ui) {
            var list = ui.item.children('ul').attr('id').replace('list_', '');
            window.alert('Moving list ' + list + ' to position ' + ui.item.index());
        },
    });
    $(".list").sortable({
        connectWith: ".list",
        forcePlaceholderSized: true,
        stop: function(event, ui) {
            var item = ui.item.attr('id').replace('item_', '');
            var list = ui.item.parent().attr('id').replace('list_', '');
            window.alert('Moving item ' + item + ' to list ' + list + ' position ' + ui.item.index());
        },
    });
});

I love jQuery and jQuery UI.