I'm aware of doing that 'magic' inside $.when(). How should I achieve same effect writing code more readable ? I read something about a $.Defferer() that I think should help but I don't know how to use it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.when(
$('.elm').each(function(index){
$(this).delay(800*index).animate({'opacity': '0'},1000);
})
).then(function(){
$('.console').find('p').text("all animations done");
});
});
</script>
</head>
<body>
<div class="console"><p></p></div>
<div class="elm"><h1>Element 1</h1></div>
<div class="elm"><h1>Element 2</h1></div>
<div class="elm"><h1>Element 3</h1></div>
</body>
</html>
What I want is to run multiple animations and at the end of them to show a message, to do something. I know that I can use $(".elm").animate() and all elm
divs will be animated by I use that .each()
to set the delay between them (maybe there's another posibility using animation step
or progress
handlers), but I can't get it to do something at the end of all
animations. What I ask is if there's any other implementation that will to same thing and be more code readeable.
-
\$\begingroup\$ While your question is good, I would add a bit of explanation about what your code really do. \$\endgroup\$Marc-Andre– Marc-Andre2014年09月17日 15:12:53 +00:00Commented Sep 17, 2014 at 15:12
1 Answer 1
I'd say your approach is correct. Since your delay is less than the duration, you can't use a series approach, where one completed animation starts the next. So your setup is probably the simplest you can do.
To make it more readable, the simplest thing would be to split the code up a bit:
$(function () { // same as $(document).read(...)
// declare some "constants"
var animationDelay = 800,
animationDuration = 1000;
// setup all the animations
var queue = $(".elm").each(function (i) {
$(this).delay(i * animationDelay).animate({opacity: 0}, {duration: animationDuration});
});
// set up the callback for when they finish
$.when(queue).then(function () {
// all animations done
});
});