Reputation: 29
I've got a jquery function that animates list items in sequence. It's working well, but I'd like it to repeat once all list items have been animated. I know this is probably simple but I can't figure it out :(
$('ul').each(function() {
$(this).children().each(function(i) {
$(this).delay((i++) * 1000).animate({opacity:0});
});
$(this).children().each(function(i) {
$(this).delay((i++) * 0).animate({opacity:1});
});
});
Upvotes: 0
Views: 144
Reputation: 2370
This will repeat animation for all ul
lists only after every li
item under it finishes its animation.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('ul').each(function() {
animateUl(this);
});
});
function animateUl(elementUl) {
$(elementUl).children().each(function(i) {
$(this).delay((i++) * 1000).animate({
opacity: 0
});
$(this).delay((i++) * 0).animate({
opacity: 1
});
});
setTimeout(animateUl, $(elementUl).children().length * 1000, elementUl);
}
</script>
</head>
<body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</body>
</html>
Upvotes: 1
Reputation: 12629
Simply create one function animate()
and call itself recursively
. Use setTimeout
of $(ul).children().length * 1000
to set delay in calling function.
I guess you are having multiple such ul
. So animation need to repeat based on number of li
for respective ul
.
function animate(ul) {
$(ul).children().each(function(i) {
$(this).delay((i++) * 1000).animate({opacity:0});
});
$(ul).children().each(function(i) {
$(this).delay(0).animate({opacity:1});
});
// Call for repeatedly animate once all animations are done.
// Use timeout of $(this).children().length * 1000 to set delay in calling function.
setTimeout(animate, $(ul).children().length * 1000, ul);
}
// Initiate animation.
$('ul').each(function() {
animate(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Upvotes: 1