Danis
Danis

Reputation: 2110

Keyframe loop animation resulting in compilation error

I'm trying to create Less loop, to animate the coins left and top position with CSS. I've created some Less mixin that creates a keyframes and assign it to current element, but I'm getting the Less error. Can someone say, what's wrong with this code?

.boom (@index) when (@index > 0){
   @keyframes boom@index {
       0% {
          top: 50%;
          left: 50%;
       }
       50%{
          top: random(2500)+px;
          left: random(2500)+px;
       }
   }
   .coin:nth-child(@{@]index}){
        left: unit(@{i}* 10, px);
        animation-duration: 2.6s;
        animation-name: boom-@{i};
        animation-direction: alternate;
        animation-timing-function: ease-in-out;
  }
  .boom(@index - 1);
}
.boom(5);

Upvotes: 1

Views: 557

Answers (1)

Harry
Harry

Reputation: 89780

I think there are a couple of typo errors in the code given in question as @{i} is used in a few places. I assume they were intended to be @{index}.

Other than that, the following were the corrections:

  • When you give @keyframes boom@index, first of all you have to use the variable in the form @{} because the variable is being used in a selector (sort of). This is to avoid Less compiler treating it like it is a CSS @ rule.
  • After that there is a typo error again in the line .coin:nth-child(@{@]index}). There is an extra @ and a ] brace.
  • Finally, even if we ignore the @{i} and @{index} confusion, the code animation-name: boom-@{i}; will cause a problem because when you try to concatenate a variable with a string without enclosing them in quotes it would produce an error.
  • Note: random(2500)+px will not cause any compilation errors but there is no built-in random() function in Less and + is not used for string concatenation (unless you are using LessPHP like mentioned by seven-phases-max in comments). I think you were probably looking for something like unit(`Math.random(2500)`,px).
.boom (@index) when (@index > 0){
    @keyframes ~"boom@{index}" {
       0% {
          top: 50%;
          left: 50%;
       }
       50%{
          top: random(2500)+px;
          left: random(2500)+px;
       }
   }
    .coin:nth-child(@{index}){
        left: unit(@index * 10, px);
        animation-duration: 2.6s;
        animation-name: ~"boom-@{index}";
        animation-direction: alternate;
        animation-timing-function: ease-in-out;
  }
  .boom(@index - 1);
}
.boom(5);

Upvotes: 2

Related Questions