1

i want to sort my jQuery tabs by using a 'sort attribute'

    <div id="tab1" class="tabs" sort="0"><p>TAB1</p></div>
    <div id="tab2" class="tabs" sort="2"><p>TAB2</p></div>
    <div id="tab3" class="tabs" sort="3"><p>TAB3</p></div>
    <div id="tab4" class="tabs" sort="1"><p>TAB4</p></div>

Can someone help me please?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Tupic
  • 545
  • 1
  • 6
  • 12
  • 1
    possible duplicate of [Sort Divs in Jquery Based on Attribute 'data-sort'?](http://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort) – w3spi Sep 10 '15 at 13:09

2 Answers2

1

jQueryUi Tabs are good but they cannot be auto-sorted since there is no native function of the same, but i have created a custom solution for it.

What I have done:

  • Sorted the DOM structure based on the id of each li(tab) in ascending order.
  • Updated the li(tabs) with sorted li(tabs).
  • called jQueryUi .tabs() to render the list as tabs.

HTML CODE:

<div id="tabs">
<ul>
    <li id="1"><a href="#tabs-1">Nunc tincidunt</a>
    </li>
    <li id="3"><a href="#tab3">Aenean lacinia</a>
    </li>
    <li id="2"><a href="#tabs-2">Proin dolor</a>
    </li>
</ul>
<div id="tabs-1">
    <p>1.</p>
</div>
<div id="tabs-2">
    <p>2.</p>
</div>
<div id="tab3">
    <p>3.</p>
</div>

JS CODE:

$(function () {
 //sort the tabs 
 sortTabs('#tabs');
 var tabs = $("#tabs").tabs();

 function sortTabs(target) {
    var sortedTabs = $(target).find("li").sort(function (a, b) {
        if (a.id < b.id) {
            return -1;
        } else {
            return 1;
        }
    });
    //update the sorted DOM
    $(target).find('ul').html(sortedTabs);
 }
});

Live Demo @ JSFiddle

dreamweiver
  • 6,002
  • 2
  • 24
  • 39
0

Wrap all tab division in one division like;

 <div class='tab-container'>
     <div id="tab1" class="tabs" sort="0"><p>TAB1</p></div>
     <div id="tab2" class="tabs" sort="2"><p>TAB2</p></div>
     <div id="tab3" class="tabs" sort="3"><p>TAB3</p></div>
     <div id="tab4" class="tabs" sort="1"><p>TAB4</p></div>
 </div>

 $('.tab-container').sort(function (a, b) {

  var contentA =parseInt( $(a).attr('data-sort'));
  var contentB =parseInt( $(b).attr('data-sort'));
  return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
 });
Chintan7027
  • 7,115
  • 8
  • 36
  • 50