javascriptcssanimationtransform

how can I do the transform first then animation in js?


I want the item1 can be larger and rotate first, and then keep spinning, however the result shows that it only excutes the animation but transform. Thank you for your help.

In css

#item1 {
    transition: transform 3s ease-in-out;
    animation: spin 10s linear infinite;
    animation-play-state: paused;
}

@keyframes spin{
    0%{
        transform: rotate(0deg);
    }

    100%{
        transform: rotate(360deg);
    }
}

In js

button.onclick = function () {
  item1.style.transform = "scale(1.2) rotate(360deg)";
  setTimeout(function () {
    item1.style.animationPlayState = "running";
  }, 3000);
};

Solution

  • It seems there is no way to run transform "rotate and scale" in single animation keyframes. You have to create two DIVs. One for rotate and one for scale. You can then add JavaScript "setTimeout" for some delay.

    function stopAnime(){
    document.querySelectorAll(".animeCLS").forEach(element => {
                element.style.animation="none"; // Stop all animations.
            });
    }
    function startAnime(){
    document.querySelectorAll(".parentRotate").forEach(element => { 
                element.style.animation="rot 2s infinite linear"; // Start rotating animations.
            });
    document.querySelectorAll(".childScale").forEach(element => {
                element.style.animation="scl 2s infinite linear"; // Start scaling animations.
            });
    }
    .parentRotate{animation:rot 2s infinite linear;width:200px;height:200px;background-color:black;border-radius:50%;}
    .childScale{animation:scl 2s infinite linear;width:200px;height:200px;background-color:yellow;border-radius:50%;}
    @keyframes rot{
    from{transform: rotate(0deg);}
    to{transform: rotate(360deg);}
    }
    @keyframes scl{
    0%{transform: scale(0.8);}
    50%{transform: scale(1.2);}
    100%{transform: scale(0.8);}
    }
    <div class="parentRotate animeCLS" style="">
    <div align="center" class="childScale animeCLS" style="">text</div>
    </div>
    
    <button onclick="startAnime();">startAnime</button>
    <button onclick="stopAnime();">stopAnime</button>