Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stagger jQuery Animations

I want to animate a series of items in jquery 1.3, with each next item beginning halfway through the first animation. In otherwords, I want a half-queue effect. I attempted to use the below code, but it is not working. Does anyone have any ideas?

    $("h3").click(function(){
      $(".projectItem").each(function (i) {
        if (i > 0){
            setTimeout ("", 500);
        }
        $(this).animate({"opacity": 0, "duration": 1000});
      });
    });

PS: I attempted to use various "idle" or "pause" jquery plugins, but I suspect the techniques used were pre jquery 1.3?

PPS: Thanks in advance for your help :)

like image 255
Matrym Avatar asked Dec 30 '09 18:12

Matrym


2 Answers

You could try something like this:

$("h3").click(function(){
  $(".projectItem").each(function (i) {
    // store the item around for use in the 'timeout' function
    var $item = $(this); 
    // execute this function sometime later:
    setTimeout(function() { 
      $item.animate({"opacity": 0}, 1000);
    }, 500*i);
    // each element should animate half a second after the last one.
  });
});

The general idea here is using your list of .projectItem - you delay the animation from beginning until 500ms per item. The first item (i=0) will have a 0ms delay and execute (almost) immediately during the next event loop. Each other item will be delayed by 500ms per item before it, and since your animation lasts 1000ms, it will start approximately halfway through the last items animation.

like image 121
gnarf Avatar answered Oct 30 '22 06:10

gnarf


I think it's simpler to break the animation to 2 parts (from opacity 1 to 0.5, and from 0.5 to 0) and use regular queue (if the breaking is possible).

This code is if we start at opacity 1:

$("h3").click(function(){
  $(".projectItem").each(function (i) {
    $(this).animate({"opacity": 0.5, "duration": 500}, function(){
      //... put here something in the half way ...
      $(this).animate({"opacity": 0, "duration": 500}); 
    });
  });
});
like image 41
Yaakov Shoham Avatar answered Oct 30 '22 06:10

Yaakov Shoham