Search code examples
javascriptjquerycssanimationstylesheet

How do I run this piece for css code through javascript


Thanks for taking out the time to look into this and any help in this regard is appreciated.

I have the following piece of code.

.middle_n.expand.remove
{
 animation: contractm 0.3s forwards;
 transform-origin: 0 75px;
 height:200%;
 animation-delay: 1.3s;
}

@keyframes contractm 
{
 0%{}
 100%{transform:translate(147.8%,100%) rotate(-16.75deg);}
}

I wish to pass a dynamic value to rotate in contractm through javascript. How do I do that. Can multi step animation run through javascript?

Thanks again.


Solution

  • In my opinion, if you want to control your animation rather than just let it animate, my recommendation is that you can use js to control the style of your element. Because animation is to complete a series of animation.

    And there is a really powerful css called css variable, you can take more details on https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties.

    const rotate=document.getElementById("rotate")
    let r=0
    rotate.addEventListener("click",()=>{
      r += 10
      rotate.style.setProperty("--rotate", r+"deg");
    })
    #rotate{
      --rotate:0deg;
      background:pink;
      width:100px;
      height:100px;
      transform:rotate(var(--rotate));
      transition:transform 1s;
    }
    <p>click the square and then it will rotate.</p>
    <div id="rotate"></div>

    Of course, if you want a series of animations, you can check it on https://developer.mozilla.org/en-US/docs/Web/CSS/animation. It's easy to set steps in animation.