1

jsFiddle example

I'm attempting to use an ol to display several, dynamic, list items. Upon appending a list item using jQuery, I'd have hoped that the browser would've refreshed the ordered list, however it doesn't appear to be.

<ol>
    <li value="1">First</li>
    <li value="2">Second</li>
    <li value="4">Forth</li>
</ol>

After appending <li value="3">Third</li>, the resulting order is:

// First
// Second
// Forth
// Third <-

Do I need to trigger a re-order, or is the order only calculated upon rendering the page / adding the list DOM element?

Note: I'm using Chrome 28.0.1500.95m

Richard
  • 8,110
  • 3
  • 36
  • 59
  • I don't think the browser ever orders a list -- see [this fiddle](http://jsfiddle.net/q89hG). You can use [something like this](http://jsfiddle.net/VdrDD), though. – Petr R. Aug 19 '13 at 10:51
  • See http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener - to be honest, it'll be easier to trigger the sort yourself after adding the item. – cmbuckley Aug 19 '13 at 10:52

1 Answers1

2

Firstly, note that value is not a valid attribute of li, so your code is invalid. You should use a data attribute for any non-standard attributes you require, the you need to write a sorter function. Try this:

$('#addThird').one('click', function() {
   $('ol').append('<li data-value="3">Third</li>');
    sortItems();
});

var sortItems = function() {
    var $items = $('ol li');
    $items.sort(function(a, b) {
        var keyA = $(a).data('value');
        var keyB = $(b).data('value');
        return (keyA > keyB) ? 1 : 0;
    });
    $.each($items, function(index, row){
        $('ol').append(row);
    });
}    

Updated fiddle

This sorts by the data-value attribute of the element, but that can be amended as required.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339