patternjavascriptMinor
A partially overlapping sequence of jQuery animations
Viewed 0 times
sequencepartiallyanimationsoverlappingjquery
Problem
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();Solution
@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
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.
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.
Code Snippets
(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);
}());Context
StackExchange Code Review Q#59781, answer score: 7
Revisions (0)
No revisions yet.