Home > Mobile >  I want to pause/play CSS animation using one button with Javascript. The sun and sky colors should b
I want to pause/play CSS animation using one button with Javascript. The sun and sky colors should b

Time:04-09

HTML CODE:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset = "utf-8">
        <title>Keyframe Animations</title>
        <link rel="stylesheet" href="SunLabcss.css" type="text/css"/>
        <script src="scriptSun.js"></script>


    </head>
    <body>
        <button id = "sunButton" onclick="sunPausePlayToggle()">PLAY/PAUSE</button

sunPausePlayToggle() is a function in JS which will control the animation .

        <div id = "sunSky"

this is a div which i am using as a background sky

            <div id = "sun"></div

the upper div is a sun which rise from right and dawn in the left

        </div>
    </body>
</html>


CSS code:

I am using keyframe animations to animate the sun and sky.

@keyframes risesky {
    0% {
        top: 100%;
        left : 100%;
        background-color: red;
    }
    50% {
        left:50%;
        top: 10%;
        background-color: yellow;

    }
    100% {
        background-color: orangered;
        top: 100%;
        left: 0%;
    }
}

@keyframes sky {
    0% , 100% {
        background-color: #1c1341;

    }
    10% {
        background-color: darkorange;
    }
    50% {
        background-color: skyblue;

    }
    80% {
        background-color: crimson;

    }
}

#sunButton{
    animation-play-state: running;
}

#sun {
    position: relative;
    border-radius: 50%;
    width: 80px;
    height: 80px;
    animation: risesky 11s infinite;

}

#sunSky {
    height: 500px;
    overflow: hidden;
    animation:  sky 11s infinite both;
    
}


Javascript code:

here is the problem I am getting, I can only pause the animation in JS ,but can't play.

function sunPausePlayToggle(){
    document.getElementById("sunSky").style.animationPlayState = "paused";
    document.getElementById("sun").style.animationPlayState = "running";
    
}

CodePudding user response:

Turn #sunButton = animation-play-state: "paused"; in css

And this is the js

function sunPausePlayToggle(){
    let sunsky = document.getElementById("sunSky")
    let sun = document.getElementById("sun")
    
    const sky_sty = sunsky.style.animationPlayState === 'running';
    const sun_sty = sun.style.animationPlayState === 'running';

    sunsky.style.animationPlayState = sky_sty ? 'paused' : 'running';
    sun.style.animationPlayState = sun_sty ? 'paused' : 'running';
    
}
  • Related