1

I'm building an animation where I want a series of <div>s to appear over time (changing their opacity from 0 to 1), in an order that I assigned to them. So far, I've got the first part working: the <div>s appear on the screen one by one.

This is my HTML:

<div id="parent_container">
<div n="2">1</div>
<div n="1">2</div>
<div n="3">3</div>
<div n="4">4</div>
<div n="5">5</div>
<div n="7">6</div>
<div n="6">7</div>
<div n="8">8</div>
<div n="9">9</div>
</div>

(With some CSS for background color, opacity, etc.) And this is my function:

var delay = 0;
$('div').each(function(){
    $(this).delay(delay).animate({
        opacity:1,
    },500);
    delay += 500;
});

You can fiddle with my code here: http://jsfiddle.net/VS8tQ/250/

But now I want to sort those <div>s as the animation is running, so that <div n="1"> (in this case '2') appears before <div n="2"> (in this case '1'). What I need seems to be very similar to a question that was asked here: How to sort DOM elements while selecting in jQuery? (the solution of which has been copied as a comment in the above fiddle). But I can't seem to get it to work with a different attribute than @id, which is a problem for me (because I need that attribute for something else).

Any suggestions?

Community
  • 1
  • 1

1 Answers1

0

You can use the following to sort the elements:

Updated Example

$('.circle[n]').sort(function(a,b) {
     return $(a).attr('n') > $(b).attr('n');
}).appendTo('#parent_container');
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Thank you!! This is the result: http://jsfiddle.net/VS8tQ/253/ It works perfectly! – Wout Dillen Sep 01 '14 at 19:40
  • The order I'm working with IRL is a lot longer than the one I had in the example; and I've noticed that Chrome has difficulties with the longer list. Works fine in Firefox & Safari, but Chrome animates them in a random order, not the sort()-ed one - even with as little as 20 items. Do you know what Chrome's problem is? And if there's a way to fix it? – Wout Dillen Sep 05 '14 at 09:20
  • @WoutDillen If you post an example, I'll take a look at it. – Josh Crozier Sep 05 '14 at 12:29