0

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/

10
  • How do you want to solve it? Reset the animation when clicked the second time? Or don't start a new one? Commented Apr 26, 2014 at 17:33
  • 2
    Might $('.service').stop().fadeOut(); do the trick? Commented Apr 26, 2014 at 17:34
  • The ideal will we to don't start a new one, but It really don't matter if the current animation is reseter or the new one is canceled Commented Apr 26, 2014 at 17:35
  • PhistucK, let me try that Commented Apr 26, 2014 at 17:36
  • 3
    As the docs say, don't use .delay() for anything where you need any control over the timer. Use setTimeout() instead and cancel the timer when the link is clicked again. Commented Apr 26, 2014 at 17:37

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be better if the if(i == $('.service').length - 1) {...} is placed in a callback, like this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.