Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stagger multiple animation delays in Sass?

Tags:

css

for-loop

sass

I was wondering how I can calculate two animation delays (fade in and fade out) by using a for loop in Sass.

Came up with the following, but doesn't know how to calc the second animation delay.

@for $i from 1 through 2 {
    .text:nth-child(#{$i}) {
        animation-delay: ($i * 0.5s), 4s;
    }
}

I would like to do the same for the fade in, so each text element will be slightly stagger.

Already tried something like this, but with no result.

@for $i from 1 through 2 {
    .text:nth-child(#{$i, $a}) {
        animation-delay: ($i * 0.5s), ($a * 0.5s);
    }
}

And how can I use the last delay to start another delay of another animation?

like image 840
Caspert Avatar asked Nov 07 '22 17:11

Caspert


1 Answers

I'm not sure exactly what you're trying to accomplish.

The easy version

That said, the basic idea is to do the "in" and "out" animations as percentages of the same animation function. In this case the build in = 25%, static = 50%, and build out = 25%.

Then your duration controls how long each part takes to complete. In this case 2 seconds.

Next, the delay (calculated as part of the loop) offsets the animation. You could also multiply the duration in the loop to completely stagger the animation.


$timeOffset: 0.5s;
$aniLength: 2s;
// 0.5s in, 1s solid, 0.5s out = 2sec

.item {
    opacity:0;
    animation-name: animation;
    animation-duration: $aniLength;
    animation-timing-function: ease-in-out;
}

@for $i from 1 through 20 {
    .item:nth-child(#{$i}){
        // units are in the variable so SCSS just does math
        animation-delay: $i * $timeOffset;
    }
}

@keyframes animation {
    0% {
        opacity: 0;
        transform: translatex(100%);
    }
    25% {
        opacity: 1;
        transform: translatex(0);
    }
    75% {
        opacity: 1;
        transform: translatex(0);
    }
    100% {
        opacity: 0;
        transform: translatex(-100%);
    }
}

Here's a Codepen example since SO doesn't parse SCSS in the code sandbox available here.

More complex version with multiple delays

Your second example didn't work because you were building an odd selector in your nth-child code while using an undefined variable.

Also, you can do pretty complex math for each iteration. Just remember concepts like Order of Operations.

The correct way to specify two different delay values is like this:

@for $i from 1 through 20 {
        // the hash forces SCSS to create a string
    .item:nth-child(#{$i}){
        // you need to use $i for BOTH since its the only defined increment
        animation-delay: $i * $timeOffset, $i * $timeOffset + $aniLength;
        // delay #1 = iteration * 0.5s, delay #2 = iteration * 0.5s + 2s (run at end of animation plus the offset)
    }
}
like image 89
Bryce Howitson Avatar answered Nov 12 '22 16:11

Bryce Howitson