# Shortening/refactoring jQuery animation code

I know this is a mess! How can I write this code better?

function anim() {
$( "#p1-animation-1" ).fadeIn( 1200, function() {$( "#p1-animation-1" ).fadeOut( 1200 );
$( "#p1-animation-2" ).fadeIn( 1200, function() {$( "#p1-animation-2" ).fadeOut( 1200 );
$( "#p1-animation-3" ).fadeIn( 1200, function() {$( "#p1-animation-3" ).fadeOut( 1200 );
$( "#p1-animation-4" ).fadeIn( 1200, function() {$( "#p1-animation-4" ).fadeOut( 1200 );
$( "#p1-animation-5" ).fadeIn( 1200, function() {$( "#p1-animation-5" ).fadeOut( 1200 );
$( "#p1-animation-6" ).fadeIn( 1200, function() {$( "#p1-animation-6" ).fadeOut( 1200 );
anim();
});
});
});
});
});
});
}
anim();

-
you need some kind of loop to do this –  paritosh Aug 12 at 11:13
See this jsfiddle might help you ,jsfiddle.net/uWGVN/2 –  paritosh Aug 12 at 11:19
That's what i was looking for, Thank You! –  Fede Aug 12 at 11:22

@Paritosh has suggested some code to change what you have done, but doesn't explain it at all.

The suggestion is that you use a loop

(function loop() {
$('.elements').each(function() { var$self = $(this);$self.parent().queue(function (n) {
});
}).parent().promise().done(loop);
}());


This is the code taken from Paritosh's JSFiddle

all that is being done here is that you are sending a node as a parameter to the function and then it is going through each child node of that node, fading it in and then fading it out.

This is much more efficient and can be used on any Node, in other words you can reuse this code where as the original code couldn't be reused unless you changed all the ID's.

-
One small point: I believe in code in the question, when an elements fades out, then the next element fades in simultaneously. However in your/Paritosh's code the next element doesn't fade in until the previous element has faded out. –  RoToRa Aug 12 at 14:37
@RoToRa, would you mind providing a JSFiddle? Then we can compare and see the difference and check between browsers, etc. –  Malachi Aug 12 at 15:07