Home > Mobile >  JQuery animates activating not in right order
JQuery animates activating not in right order

Time:05-05

I develop a JQuery animation for my streams. When a viewer buy a reward, an announcement appears on the screen.

The animation should display like this:

  1. A half opaque bar expands
  2. Titles slide in the center of the bar
  3. Titles slide out of the bar
  4. The bar shrinks to void

Nonetheless the fact that the delays look consistent to display the animation one after the other, the 3) and the 4) steps are playing at the same time.

const transition_duration = 1250;

let wait = 1000;
$('#announcement').delay(wait).animate({height: $('#announcement')[0].scrollHeight, padding: '10px 0 10px 0'}, transition_duration);

wait  = 1000   transition_duration;
$('#title-container').delay(wait).animate({left: `${($(window).width() - $('#title-container')[0].scrollWidth) / 2.}px`}, transition_duration);
$('#subtitle-container').delay(wait).animate({left: `${($(window).width() - $('#subtitle-container')[0].scrollWidth) / 2.}px`}, transition_duration);

wait  = 4000   transition_duration;
$('#title-container').delay(wait).animate({left: `-${$('#title-container')[0].scrollWidth}px`}, transition_duration);
$('#subtitle-container').delay(wait).animate({left: `100%`}, transition_duration);

wait  = 1000   transition_duration;
$('#announcement').delay(wait).animate({height: 0, padding: 0}, transition_duration);

Thanks for your help

CodePudding user response:

Your issue with d and e is that they the second delay animation is queued after the first delay animation, it's not a separate delay animation.

Consider:

$("#id")
    .delay(100)
    .animate(..., 100, () => log(200))
    .delay(100)
    .animate(..., 100),() => log(400))

the last would be 400 as it's 100 100 100 100.

In your code, it's the same, except you have:

$("#id")
    .delay(100)
    .animate(..., 100, () => log(200));
// some other code
$("#id")
    .delay(100)
    .animate(..., 100),() => log(200))

the last log should still be 400, not 200, as it's the same code as before, just split across two "lines".

This is because each .delay and .animate gets added to the same queue for the #id.

Chaining/not chaining has no impact, the animate doesn't wait 100 because it's chained to .delay, it waits 100 because there's a delay in the queue, ie the same as:

$("#id").delay(100);
$("#id").animate(..., 100, () => log(200));

So you either need to adjust your .delay time to remove the previous delay animate, eg .delay(wait - 1000 - duration), or use multiple "queues".

https://api.jquery.com/delay/

.delay( duration [, queueName ] )

So the sample above becomes:

$("#id")
    .delay(100, "q1")
    .animate({ animation }, { duration: 100, queue: "q1", complete: () => log(200) });

$("#id")
    .delay(300, "q2")
    .animate({ animation }, { duration: 100, queue: "q2", complete: () => log(400) });
  • Related