0

I've seen a few examples out there, but not finding a way to sort a list onload.

In this example by Jennifer Perrin, she shows how to sort with two links (sort ascending/sort descending).

Can you offer a tweak to do this on page load instead?

markup

<h1>Sort by:
<a href="#" class="link-sort-list asc">Desc</a>
<a href="#" class="link-sort-list desc">Asc</a>
</h1>

<ul id="sort-list">
<li>Orange</li>
<li>Pear</li>
<li>Bananna</li>
<li>Apple</li>
<li>Cucumber</li>
</ul>

jquery

$(document).ready(function() {
$('.link-sort-list').click(function(e) {
    var $sort = this;
    var $list = $('#sort-list');
    var $listLi = $('li',$list);
    $listLi.sort(function(a, b){
        var keyA = $(a).text();
        var keyB = $(b).text();
        if($($sort).hasClass('asc')){
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA < keyB) ? 1 : 0;
        }
    });
    $.each($listLi, function(index, row){
        $list.append(row);
    });
    e.preventDefault();
});
});
Alan
  • 29
  • 2
  • 7
  • 1
    Remove the `click` handler? – six fingered man Dec 12 '14 at 15:28
  • If there are multiple `link-sort-list` elements, then just replace `click` with `each`, and you're set. – six fingered man Dec 12 '14 at 15:29
  • Thanks. I think this would work, but the site is already sorting on weight using yui. I thought jQ at

    would 'win' (override) but apparently not. With the example below, http://stackoverflow.com/a/27446872/2368444 at-least the list gets put into *CLOSE-TO* descending alpha. A real head-scratcher.

    – Alan Dec 12 '14 at 16:11

1 Answers1

0

Just use this without the click function

$(document).ready(function() {
    var $sort = $('.asc');
    var $list = $('#sort-list');
    var $listLi = $('li',$list);
    $listLi.sort(function(a, b){
        var keyA = $(a).text();
        var keyB = $(b).text();
        if($($sort).hasClass('asc')){
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA < keyB) ? 1 : 0;
        }
    });
    $.each($listLi, function(index, row){
        $list.append(row);
    });
    e.preventDefault();
});

Here I have set $sort as asc. But you can feed the req value from any variable. Hope this works.Thanks

Biswas
  • 598
  • 2
  • 16
  • 34