7
\$\begingroup\$

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();
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Aug 12, 2014 at 10:22
\$\endgroup\$
2
  • \$\begingroup\$ you need some kind of loop to do this \$\endgroup\$ Commented Aug 12, 2014 at 11:13
  • 1
    \$\begingroup\$ See this jsfiddle might help you ,jsfiddle.net/uWGVN/2 \$\endgroup\$ Commented Aug 12, 2014 at 11:19

1 Answer 1

7
\$\begingroup\$

@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) {
 $self.fadeIn(2000).delay(200).fadeOut(2000, 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 whereas the original code couldn't be reused unless you changed all the ID's.

answered Aug 12, 2014 at 13:31
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Aug 12, 2014 at 14:37
  • \$\begingroup\$ @RoToRa, would you mind providing a JSFiddle? Then we can compare and see the difference and check between browsers, etc. \$\endgroup\$ Commented Aug 12, 2014 at 15:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.