public
Last active

  • Download Gist
gistfile1.mkd
Markdown

Requires a function getItemIdFromElement($element) It should take a jQuery collection, and returns an identifier for that element.

getOrder returns a flat array with object similar to the following.

{
  level: 0,
  parent: 0,
  id: 1
}

This was created for the jQuery Nested Sortable plugin.

Example implementation.

var saveOrder = function(){
    var data = getOrder($('#menu-overlay-index-menu'));

    $.ajax({
        url: '/a;menu/menuoverlay/save',
        type: 'post',
        data: { data: data },
        error: function(){
            alert('An error occurred while saving');
        }
    })
};

$('#sorted-ul-list').nestedSortable({
    [...]
    update: saveOrder
});
gistfile2.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
var getOrder = function($ul){
var $li = $ul.find('li');
var isFirst = function($element){
return $element.prev().length === 0;
};
var isLast = function($element){
return $element.next().length === 0;
};
var hasChildren = function($element){
return $element.find('> ul > li:first').length === 1;
};
var checkDepth = function($start, selector){
var level = 0;
while (true) {
$start = $start.find(selector);
if ($start.length !== 0) {
level++;
} else {
break;
}
}
return level;
};
var level = -1,
parents = [0], // parents[level] = parent_id
prevWasLastSibling = false,
data = [];
$li.each(function(){
var $self = $(this);
if (prevWasLastSibling) {
level -= checkDepth($self.prev(), '> ul > li:last');
prevWasLastSibling = false;
} else if (isFirst($self)) {
level++;
}
data.push({
level: level,
parent: parents[level],
id: getItemIdFromElement($self)
});
if (hasChildren($self)) {
parents[level + 1] = getItemIdFromElement($self);
} else if (isLast($self)) { // Don't evaluate if hasChildren
prevWasLastSibling = true;
}
});
return data;
};

Can you give an example for getItemIdFromElement($self);? I cannot figure our how to define that.

https://gist.github.com/816130

But as I said to another requester, it depends on your implementation. In our case the HTML markup is like:

<li id="menu-overlay-index-item-id-9912"></li>

getItemIdFromElement($that_li) will return 9912.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.