Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Sort <li> with jQuery

Currently I have a language select which is a simple <ul> with <li>s and <a>s inside.

Every <li> has a class - lang-inactive or lang-active. It depends on what language the user is using right now.

The <li>s with .lang-inactive are hidden by default. When you .hover() the ul the other options are showed.

Hovered - all languages Not hovered - current language

Here is a simple example.

But as you can see the first <li> is French, and when I'm using English and I hover the language bar the French appears over the english.

Is there a way I can sort the <li> depending on whether they are lang-active or lang-inactive. The inactive ones should appear below the active one.

My current code is:

var ul = $('#languages-iv');
    ul.css('position', 'absolute');
    ul.css('top', 5);
    li = ul.children('li');

    li.detach().sort(function(a,b) {
       //how do I sort
    });

    ul.append(li);
$("#languages-iv").hover(function(){
    $('.lang-inactive').slideToggle();
}, function() {
    $('.lang-inactive').stop().slideToggle();
});

Upvotes: 4

Views: 194

Answers (3)

Grzegorz
Grzegorz

Reputation: 348

    <ul>
        <li><a href="#" class="lang-active">English</a></li>
        <li><a href="#">French</a></li>
        <li><a href="#">German</a></li>
    </ul>

<script>
    $(document).ready(function(){
        $('ul li').live('click',function(){
            $('li a').removeClass('lang-active');
            var elem = $(this);
            $(this).remove();
            $('ul').prepend(elem);
            $(this).children('a').addClass('lang-active');
        });
    });
<script>

Upvotes: 2

lsouza
lsouza

Reputation: 2488

Here's your sort:

var listItems = myList.children('li').get();
listItems.sort(function(a,b){
  return $(a).hasClass('lang-inactive') ? -1 : $(b).hasClass('lang-inactive') ? 1 : 0;
});

Upvotes: 1

Andy
Andy

Reputation: 30135

This executed on page-load (or whenever your language selector gets created) should push the active language up to first child.

$('.lang-active').prependTo('#languages-iv');

Demo:

http://jsfiddle.net/gqfPV/

Upvotes: 3

Related Questions