Sorting <li> with jQuery

Currently, I have a choice of language that is simple <ul> with <li> and <a> inside.

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

<li> with .lang-inactive are hidden by default. When you .hover() ul , other options are displayed.

Hovered - all languagesNot hovered - current language

Here is a simple example.

But, as you can see, the first <li> is French, and when I use English and I set up a language bar, French appears above English.

Is there a way to sort <li> depending on whether they are lang-active or lang-inactive . Inactive should appear below active.

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(); }); 
+4
source share
3 answers

This is done when the page loads (or whenever your language selector is created) should activate the active language before the first child.

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

Demo:

http://jsfiddle.net/gqfPV/

+3
source
  <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> 
+2
source

Here is your grade:

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

Source: https://habr.com/ru/post/1495837/


All Articles