Moggz
Moggz

Reputation: 33

jQuery increment variable in recursive function

There are other questions with almost the same title as this but they don't seem to answer my question.

I am trying to make a simple javascript function that uses jQuery to fade div blocks in and out one after the other, and goes back to the first div once it get's to the end. This should continue while the user is on the page, much like a slideshow.

There are 5 'slides' or divs to be shown and hidden in sequence. They have the classes 'content1', 'content2', 'content3' etc.

$(document).ready(function() {

            var slide = 1;
            nextSlide(slide);

            function nextSlide(slide) {
                $('.content' + slide.toString()).fadeTo(2000, 1.0).delay(5000).fadeTo(2000, 0.0).delay(2000);

                if(slide > 5) {
                    slide = 1;
                } else {
                    slide++;
                }

                nextSlide(slide);
            };
        });

This does not fade each div in and out in sequence, what it actually does is fade all of the slides in and out simultaneously.

How do I get it to reference each slides class in turn and then loop back to the first slide?

Many thanks.

Upvotes: 1

Views: 1270

Answers (2)

Moob
Moob

Reputation: 16184

No need for a timeout. Simply call the next iteration as a callback of the last fadeTo method:

$(document).ready(function() {

        var slide = 1;
        nextSlide(slide);

        function nextSlide(slide) {
            $('.content' + slide.toString())
            .fadeTo(2000, 1.0)
            .delay(5000)
            .fadeTo(2000, 0.0, function(){
                if(slide > 5) {
                    slide = 1;
                } else {
                   slide++;
                }
                nextSlide(slide);
            });                
        };

});

http://jsfiddle.net/3L09b505/

Upvotes: 3

ssube
ssube

Reputation: 48257

Your function will recurse immediately, dispatching all of the animation requests around the same time.

To stagger them, you should recurse with a timeout:

$(document).ready(function() {

        var slide = 1;
        nextSlide();

        function nextSlide() {
            $('.content' + slide.toString()).fadeTo(2000, 1.0).delay(5000).fadeTo(2000, 0.0).delay(2000);

            if(slide > 5) {
                slide = 1;
            } else {
                slide++;
            }

            setTimeout(nextSlide, 2000); // second param is delay in ms
        };
    });

This will cause the next call to occur after 2000ms. Thanks to closure, your slide variable should be captured and will persist its value between calls.

Upvotes: 3

Related Questions