Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to css animation

p {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%; 
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

For the animation CSS code above, I'm wondering whether there's any way to pass the values of margin-left and width as parameter from Javascript.

like image 865
Qian Chen Avatar asked Apr 10 '18 09:04

Qian Chen


1 Answers

Use CSS variables and you can easily do this:

document.querySelector('.p2').style.setProperty('--m','100%');
document.querySelector('.p2').style.setProperty('--w','300%');
.p1,.p2 {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: var(--m, 0%);
    width: var(--w, 100%);
  }
  to {
    margin-left: 0%;
    width: 100%;
  }
}
<p class="p1">
 This will not animate as the animation will use the default value set to the variable
</p>
<p class="p2">
  This will animate because we changed the CSS variable using JS
</p>
like image 58
Temani Afif Avatar answered Oct 01 '22 23:10

Temani Afif