0

I am trying to sort a list of divs by a data attribute, using the javascript sort function.

html

<div class="boxes">
   <div data-value="0" class="box">A</div>
   <div data-value="2" class="box">B</div>
</div>

javascript

$('.box').sort(function(a,b){

    var an = parseInt(a.getAttribute('data-value')),
        bn = parseInt(b.getAttribute('data-value'));

    return an - bn;
});

It works great on Chrome except when there are more than 10 elements: in that case if I sort more than once, some elements move when they shouldn't (when their data-value attribute is the same).

I have a jsfiddle there https://jsfiddle.net/q8ovfp1b/1/ explaning the problem. If you click several times on the button on the right, the order does not change once it is set, but if you click on the button on the left, some divs are reordered, and it is always the same ones (1st, 2nd and 7th).

Is there a way to avoid this?

Agnes D
  • 431
  • 2
  • 12
  • Uh, you're not moving any elements here, you're just sorting a jQuery collection? – Bergi Jun 30 '15 at 15:26
  • 1
    The sort you're using doesn't guarantee that it won't change the order when two elements have the same value. You'll have to add some secondary sorting criteria or find an algorithm that keeps the original order on equal values. – JJJ Jun 30 '15 at 15:29
  • In your fiddle, the elements don't have different data-values. Give them a proper order and it'll work. – Bergi Jun 30 '15 at 15:30
  • 1
    Thank you @Juhana, it is working now, I [updated the fiddle](https://jsfiddle.net/q8ovfp1b/3/) – Agnes D Jun 30 '15 at 15:41

0 Answers0