eighteyes
eighteyes

Reputation: 1314

Animating a series with jQuery, why does queue work this way?

I'm fading in a series of elements left to right, and I was searching for an elegant way to do it, without using nested functions. Queue seems to save the day, but I don't understand why it is working the way it is.

This works:

$('.item').queue(function(next) {
  $(this).delay(500).animate({opacity: 1}, 1000);
});


$('.item').queue(function(next) {
  $(this).parent().next('.item').dequeue();
  next();
});


$('.intro i:first').dequeue();

This does not:

$('.item').queue(function(next) {
  $(this).delay(500).animate({opacity: 1}, 1000);
  $(this).parent().next('.item').dequeue();
  next();
});


$('.item').dequeue();

It fades them all in at once.

I had the understanding that queue appended the items in a series to be executed when an animation or dequeue fires. So... why does this work?

Upvotes: 1

Views: 55

Answers (3)

aquinas
aquinas

Reputation: 23796

I don't think that's the way the queue function works. The docs say that it is the queue on one element, not the entire queue of animations to render like I think you are trying to use it. However, it's simple to do what you're trying to do. How about this:

$(function(){
    var queue = $.makeArray($("div"));    
    (function doAnimation(){
        var item = queue.pop();
        if (item) {
            $(item).delay(500).animate({opacity: 0.8}, 1000, doAnimation);
        }
    })();    
});

JsFiddle: http://jsfiddle.net/6xdeP/1

Edit: Updated to a cleaner solution.

Upvotes: 1

Fresheyeball
Fresheyeball

Reputation: 30015

 var items  = $('.item'),
     index  = 0,
     itemInterval;

 itemInterval = setInterval(function(){
     items.eq(index).fadeIn(1000);
     index++
     if(index >= items.length){ clearInterval(itemInterval); }
 }, 500);

Just my pattern for this.

Upvotes: 1

Kaizen Programmer
Kaizen Programmer

Reputation: 3818

I'm not answering your queue question directly, because I don't really know how the animation queues work. I believe what's happening is that the animation queues are firing all at once for every $('.item')

However, I'm answering to hopefully solve your problem.

DEMO

HTML

<ul>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
</ul>

CSS

.item
{
    display:none;
   position:relative;
   float:left;    
   border:1px solid black;
   background-color:green;
    list-style:none;
    padding:10px;
}

jQuery

$.fn.ProgressiveFadeIn=function(delay,speed)
{
    if(!delay) delay=500;
    if(!speed) speed=1000;
    $(this).each(function(i){
        $(this).delay((speed+delay)*i).fadeIn(speed);
    });
}
$(".item").ProgressiveFadeIn(500,1000);

Upvotes: 1

Related Questions