SakerONE
SakerONE

Reputation: 139

How do I delay a jQuery animation after a page loads?

Here's my example: http://jsfiddle.net/UuD8s/5/

$("#transition")
    .delay(5000)
    .animate({ width: "400px" }, { duration: 1000, queue: true });

$("#transition")
    .delay(2000)
    .animate({ left: "100px" }, { duration: 1000, queue: true });​

I want to delay my second animation start after the page launches with a 2 second delay. The problem is it starts after the first animation. If queue is set to false there is no delay at all.

How would I delay the animation 2 seconds after page launch?

Upvotes: 4

Views: 12666

Answers (3)

gdoron
gdoron

Reputation: 150263

In order to delay your animation after page launch set queue to false and use a setTimeout of two seconds:

$("#transition")
    .delay(5000)
    .animate({width: "400px"}, {duration: 1000, queue: true});

setTimeout(function() {

    $("#transition").delay(2000).animate({ left: "100px" }, {
        duration: 1000,
        queue: false
    });

}, 2000);​

Here's a live demo.

Upvotes: 7

Chris
Chris

Reputation: 27609

As I understand it you want the second animation (the left one) to start 2 seconds after launch. This will take 1 second. You want the first one to start 5 seconds after launch.

So what you can do is queue them up so that two seconds after the left one finishes the width one kicks in...

$("#transition").delay(2000).animate({left: "100px"}, {duration: 1000});
$("#transition").delay(2000).animate({width: "400px"}, {duration: 1000});

http://jsfiddle.net/UuD8s/7/

This does solve it for the situation you have above where they are not running simultaneously but if you do want them to run simultaneouly (eg the width should start shrinking half way through the movement) then this will not work.

Upvotes: 0

Josh Mein
Josh Mein

Reputation: 28645

You can use the setTimeout() method to delay javascript functions.

$("#transition").delay(5000).animate({width: "400px"}, {duration: 1000, queue: true});
setTimeout(function() { 
    $("#transition").delay(2000).animate({left: "100px"}, {duration: 1000, queue: false});  
}, 2000);

Upvotes: 1

Related Questions