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();
\$\endgroup\$
  • \$\begingroup\$ you need some kind of loop to do this \$\endgroup\$ – paritosh Aug 12 '14 at 11:13
  • 1
    \$\begingroup\$ See this jsfiddle might help you ,jsfiddle.net/uWGVN/2 \$\endgroup\$ – paritosh Aug 12 '14 at 11:19
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.

\$\endgroup\$
  • 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\$ – RoToRa Aug 12 '14 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\$ – Malachi Aug 12 '14 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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