'Adding style to CSS classes in Javascript

I am trying to add an animation-play-state style to a CSS class on button click through Javascript but I am not sure where am doing it wrong. here is what I did.

function play(){
    sky.style.animation-play-state: play;
    sun.style.animation-play-state: play;
}

function pause(){
    sky.style.animation-play-state: pause;
    sun.style.animation-play-state: pause;
}

playButton.onclick = play;
pauseButton.onclick = pause;

But am getting this error in my console

Uncaught SyntaxError: Unexpected token ':'



Solution 1:[1]

Use running and paused for play and pause:

function Playpause() {
    var pauseState =   getId.style.animationPlayState === 'paused'; 
    var runState =  getId.style.animationPlayState === 'running';    
    varName.style.animationPlayState = runState ? 'paused':'running';    
}

Solution 2:[2]

You have to use camelCase to refer to CSS style properties (this is because "-" means minus in JavaScript, so the properties are all mapped to camelCase).

You also need to assign the states with "=" in JavaScript. You're using ":" which is CSS syntax.

The animation play states are also strings, so you have to wrap them in quotes.

And finally, the states you want are actually "running" and "paused", not "play" and "pause".

Here's a working snippet of what you're trying to do:

let sun = document.querySelector("#sun");
let sky = document.querySelector("#sky");
let playButton = document.querySelector("#playButton");
let pauseButton = document.querySelector("#pauseButton");

function play(){
    sky.style.animationPlayState = "running";
    sun.style.animationPlayState = "running";
}

function pause(){
    sky.style.animationPlayState = "paused";
    sun.style.animationPlayState = "paused";
}

playButton.onclick = play;
pauseButton.onclick = pause;
#sun, #sky {
  padding: 10px;
  transform-origin: center;
  
  animation-name: rotate;
  animation-duration: 8s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-play-state: paused;
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
<div style="display: flex">
  <div id="sun">Sun</div>
  <div id="sky">Sky</div>
</div>

<div>
  <button id="playButton">Play</button>
  <button id="pauseButton">Pause</button>
</div>

Solution 3:[3]

Instead of using two functions for play and pause you can instead create one and use javascript toggle method to toggle the class. And you can define animation state in the class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saransh Lakra
Solution 2 Dois
Solution 3 Hitesh