Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

animation delay, but start immediately on page load/function fire

Is there a way to animate my span tags one by one without a timeout or interval function? I could easily use keys and IDs to do this, but it doesn't seem like it would be the best way. Here is what I have in a fiddle example

Update

Nevermind the original question, from what I gather you need to use the delay() function. My only issue is, how would I start this animate immediately without using the delay for the initial animation? Updated code and fiddle below.

var credits = $('#credits'),
    container = credits.parent(),
    conPos = container.position(),
    creditsText = credits.find('span'),
    first = 0;
    delay = 1000,
    count = creditsText.length;

container.fadeIn('slow', function() {

    creditsText.each(function() {

        $(this).css({
                    'top': ( conPos.top - $(this).height() ),
                    'left': ( ( ( conPos.left + container.width() ) - $(this).width() ) / 2 )
                    }).delay(delay)
                .animate({
                            'top': ( ( ( conPos.top + container.height() ) - $(this).height() ) / 2 ),
                            'opacity': '1.0'
                        }, 
                        {
                            duration: 4000,
                            complete: function() {
                                $(this).fadeOut(5000);
                            }
                        });

        if ( first == 1 ) {
            delay = 9000;
        }

        first++;
        delay += delay;

    });

});

JSFiddle Example

You'll notice the first two 'credits' play almost at the same time, not one at a time. Then the last line takes forever to display as if on the proper timer.

like image 505
WASasquatch Avatar asked Oct 01 '22 23:10

WASasquatch


1 Answers

you can resolve this using promises:

http://jsfiddle.net/EKd99/1/

var credits = $('#credits'),
    container = credits.parent(),
    conPos = container.position(),
    creditsText = credits.find('span'),
    first = 0;
    delay = 1000,
    count = creditsText.length;

container.fadeIn('slow', function() {
  function next() {
    var span = $(creditsText.get(first));
    if (!span) return;

    $.when(
      span
      .css({
        'top': ( conPos.top - span.height() ),
        'left': ( ( ( conPos.left + container.width() ) - span.width() ) / 2 )
      })
      .animate({
        'top': ( ( ( conPos.top + container.height() ) - span.height() ) / 2 ),
        'opacity': '1.0'
      }, { duration: 4000}
      )
    ).then(function(){
      return span.fadeOut(5000);
    }).then(next);

    first++;
  }
  next();
});

we are dealing with code that must be ran in a series, and must wait for the previous to finish. promises deal with this in a nice and clean way

like image 183
pocesar Avatar answered Oct 05 '22 13:10

pocesar