Jacob
Jacob

Reputation: 2071

jQuery animate running a lot of times

I'm having problems with my animate function. I want it to just run 1 time, but it doesn't. I've tried to debug it with using .stop(); but that didn't work either, so right now I have no idea how to solve this.

The JavaScript:

$(".box").hide();

$(".box").contents().not(".progress").hide();

$(".box").first().show(150, function showNext () {

    var next = $(this).next(".box");

    if (next.length > 0) {

        next.show(150, showNext);

    } else {

        $(".box").contents().not(".progress").fadeIn(800, function () {

        $(".progress").animate({

            width: 'toggle'

        }, 800);


        });

    }
});

The problem is easier to see at this jsfiddle:

http://jsfiddle.net/etBLj/

How do I solve this?

Thanks in advance!

Upvotes: 0

Views: 44

Answers (1)

ach
ach

Reputation: 6234

The issue is that when you call $(".progress").animate(), the animation gets executed on every element with the "progress" class for the whole document. Since showNext() is called recursively, you end up with multiple animations for each matching element.

All you need to do is to restrict the call to animate to be applicable to the current element in your recursive loop. So change to $(this).next().animate and it will work.

Fiddle: http://jsfiddle.net/etBLj/1/

Additionally I think the JavaScript would become easier to understand if you separated the "showing of the headers" from the "animating of the progress bars", and replaced the recursive function with a simple each loop. For example: http://jsfiddle.net/etBLj/2/

Upvotes: 2

Related Questions