Search code examples
jqueryanimationdelay

jQuery: Multiple animations with a delay on a set of divs


I have a group of 4 divs and I'm looking to use jQuery to animate them once, then have a delay using delay(), and then run another set of animations on them, putting the divs back to their original configuration. Here's the code that I have:

//only selectors called 'option1' are affected by delay, and not 'option1 img' or 'option2'
$("#option1").showOption1().delay(3000).hideOption1();

//if i don't attach to #option1, delay doesn't work, but the animations that need to happen     simultaneously work
$(document).showOption1().delay(3000).hideOption1();

jQuery.fn.showOption1 = function(){

    $("#option2, #option3, #leftColumn").fadeOut(1000);

    $("#option1").css("zIndex", "5");

        $("#option1").animate({
        left: "370px",
        }, 1500);

    $("#option1 img").animate({ 
        width: "500px",
    }, 1500, function(){
        $("p.optionText").text('hello');
    });

 return this;
}

jQuery.fn.hideOption1 = function(){

$("#option1 img").animate({
    width: "175px",
}, 1500);


$("#option1").animate({
    left: "743px",
}, 1500);


$("#option2, #option3, #leftColumn").fadeIn(2000);

$("#option1").css("zIndex", "1");

return this;

}

I've tried two ways of running these two functions, as seen on lines 2 and 5. In the case of line 2, showOption1() will run fine, but then only

$("#option1").animate({
    left: "743px",
}, 1500);

will work from hideOption1() after the delay. The rest of hideOption1() is fired immediately after showOption1() finishes, ignoring the delay.

On the other hand, if I run line 5, all the code in hideOption1() runs simultaneously as desired, but ignores the delay entirely, running immediately after showOption1() finishes. How can I have all the code in hideOption1() run simultaneously after the delay?

Thanks much in advance!


Solution

  • .delay() doesn't exactly fit what you're trying to do, it adds a delay in the animation queue on each element that the selector matches. All the animations and delays are specific to the element, not tied to run together or the selector in any way. Since you're .fadeOut() and .animate() have different times (1000ms and 1500ms), they delay and start of the next animation is out of sync.

    Also, there's no reason for putting these functions in the jQuery object, since you're not using this inside to do anything, instead I would just have this:

    function showOption1 (){ ...code... }
    //and
    function hideOption1 (){ ...code... }
    

    Or alternatively, have the selector matches (this) actually used, hiding the other options via a class for example. To run the hide animations all at once, I'd do the functions like above, then just call them like this:

    showOption1();
    setTimeout(hideOption1, 4500); //3000 + 1500 from animation, adjust if needed