Sequential animations in Jquery
I see a lot people struggling with this(me included). I guess it's mostly due to not perfectly knowing how Javascript scopes work.
An image slideshow is a good example of this. So lets say you have series of images, the first one fades in => waits => fades out => next image.
When I first created this I was already a little lost. I think the biggest problem for creating the basics is to keep it clean. I noticed working with callbacks can get uggly pretty fast.
So to make it even more complicated most slideshows have control buttons. Next, previous, go to img, pause, ...
I've been trying this for a while now and this is where I got:
$(InitSlideshow);
function InitSlideshow() {
var img = $("img").hide();
var animate = {
wait: undefined,
start: function() {
img.fadeIn(function() {
animate.middle();
});
},
middle: function() {
animate.wait = setTimeout(function() {
animate.end();
}, 1000);
},
end: function() {
img.fadeOut(function() {
animate.start();
});
},
stop: function() {
img.stop();
clearTimeout(animate.wait);
}
};
$("#btStart").click(animate.start);
$("#btStop").click(animate.stop);
};
This code works(I think) but I wonder how other people deal with sequentials animations in Jquery? Tips and tricks are most welcome. 开发者_开发技巧So are links to good resources dealing with this issue.
If this has been asked before I will delete this question. I didn't find a lot of info about this right away. I hope making this community wiki is correct as there is not one correct answer to my question.
Kind regards,
Pickels
I guess it's mostly due to not perfectly knowing how Javascript scopes work.
Javascript scoping is function-level, not block-level. It's as simple as that. If you declare a variable using var
anywhere in a function, it's visible everywhere within that function.
With Javascript 1.7 (hint: not even remotely supported by IE) you can use the let
keyword rather than the var
keyword to declare block-scoped variables. This is more closely aligned with what Java/C/etc. programmers tend to expect.
精彩评论