views:

237

answers:

1

Hello,
first of all sorry for the strange title but I wasn't sure how to call this. I am trying to create a slideshow for images. Actually it's more like a fade in and out show.

I could explain the whole thing but I think it's a lot clearer if I just posted my code.

var Images = ["images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg"]
var ImageContainer = $("#Images");
var Image = $("<img />");
var Counter = 0;

var Animate = {
    Start: function() {
        var that = this;
        Image.attr("src", Images[Counter]);
        ImageContainer.append(Image.fadeIn(that.Middle()));
    },

    Middle: function() {
        var that = this;
        setTimeout(function() {
            that.End();
        }, 2000);
    },

    End: function() {
        var that = this;
        Image.fadeOut(function() {
            Counter = Counter + 1;
            that.Start();
        })
    }
}

Animate.Start();

$("#Button").click(function() {
    //Stop the animation; //Change counter value; //Start animation
});

So my main question is: how do I do the stop, change and start function. My second question is: is this a good way of chaining the events? I tried other ways before but they turn ugly really fast. I also aint really a javascript expert so maybe there is some really weird code in my example. Code like "var that = this;" makes me think I am doing it wrong.

Kind regards Pickels.

+1  A: 

After reading this you will be able to answer your own question. You can replace var that = this; by using call or apply (there is already a lot of docs and questions about that).

Matias
It wasn't my main question but thanks for answering it.
Pickels
Sorry, I did not understand the direction of the question.Does it work if you call Animate.End(); ?
Matias
Well End() just does some stuff and then calls start again. So calling End() doesn't stop it. But I think I fixed it by making a function Stop() that calls the jquery stop() to stop the fadein or fadeout.
Pickels