Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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();
share|improve this question
    
you need some kind of loop to do this –  paritosh Aug 12 at 11:13
1  
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

1 Answer 1

up vote 7 down vote accepted

@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 where as the original code couldn't be reused unless you changed all the ID's.

share|improve this answer
1  
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.