Vivek Dragon
Vivek Dragon

Reputation: 2248

Append function at certain Interval

I am having 3 div which have a simple animation to slide from right to left. How to set intervals by applying functions to them.

For example 2nd div should slide at 1st delay and should animate after 3rd like that.

Html

<div class="Objects"></div>
<div class="Objects"></div>
<div class="Objects"></div>
<button class="trigger">Click Me</button> 

Css

.Objects{ width:200px; height:100px; background:#ccc; margin:10px; position:relative; left:500px;}

Script

$(".trigger").click(function () {
  $(".Objects").animate({left:'0px'});
});

Working Link

http://jsfiddle.net/vivekdx/xZn3u/

Upvotes: 1

Views: 354

Answers (3)

S. Rasel
S. Rasel

Reputation: 2959

Please try the following code and it will work for you..

$(".trigger").click(function (){
   var el = $(".Objects");
   $.each( el, function( key, value ) {
     var tm = 1000*key;
     $(value).delay(tm).animate({left:'0px'});
   });
});

Please take a look at following link to see the output

http://jsfiddle.net/xZn3u/4/

Upvotes: 2

R. Oosterholt
R. Oosterholt

Reputation: 8090

jQuery's animate has a 'complete' property which is called when the animation is completed. Example:

$item.animate({left:'0px'}, function() {
    // next call
});

see api

Upvotes: 0

Jo David
Jo David

Reputation: 1746

I'm using the setTimeout command. It executes a function after a specified delay.

While iterating over the jQuery Array containing the selected divs, I multiply the base delay with the current index. So every call to the slideLeft function is delayed more with each iteration.

I changed your script to the following:

var slideLeft = function($item) {
    $item.animate({left:'0px'});
}

$(".trigger").click(function () {
//      $(".Objects").animate({left:'0px'});

    $(".Objects").each(function(index, item) {
        setTimeout(slideLeft, 200 * (index + 1), $(item));
    });

});

Working demo based on your fiddle: http://jsfiddle.net/xZn3u/1/

Upvotes: 3

Related Questions