Question

I had a function that looks like this

function show_services_title(show_services){
    $('.service').fadeOut();
    $.each($('.service'), function(i) {
        $(this).delay(500*i).fadeIn();
    });
}

Now, this functions is invoked when I click on a link, the problem is that when I click the link the function start to show each div with the class 'service', but when I click the link again and the divs haven't finish showing yet then occur a mess in the screen.

Here is an example that simulate the behavior I'm trying to describe and I want to avoid.

http://jsfiddle.net/bw7jn/4/

Was it helpful?

Solution

Try to disable running the animation the second time when the previous animation is still running.

$(document).ready(function(){
    $('#link').click(function(){
        show_services_title();
    });
});

function show_services_title(show_services){

    //if we're already animating, don't start a new one
    if($('ul').attr('data-animating') != 'true'){

        //make sure other clicks dont trigger this animation
        $('ul').attr('data-animating', 'true');
        $('.service').fadeOut();
        $.each($('.service'), function(i, element) {
            setTimeout(function(){
                $(element).fadeIn();

                //check if this is the last element we're gonna animate
                if(i == $('.service').length-1){
                    //animation is done, allow new animations to start
                    $('ul').attr('data-animating', 'false');   
                }
            }, 500*i);
        });
    }
}

http://jsfiddle.net/bw7jn/7/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top