Sequential animations in Jquery

Posted by Pickels on Stack Overflow See other posts from Stack Overflow or by Pickels
Published on 2010-03-30T18:29:21Z Indexed on 2010/03/30 18:33 UTC
Read the original article Hit count: 276

Filed under:

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

© Stack Overflow or respective owner

Related posts about jQuery