Eva Aggarwal
Eva Aggarwal

Reputation: 1

How to ensure my CSS animation doesn't restart onClick

I made a small CSS animation of a vinyl record png picture being rotated with the following code:

.vinyl-record-playing {
  height: 500px;
  width: 500px;
  animation: spin 10s linear infinite forwards;
}

.vinyl-record-paused {
  height: 500px;
  width: 500px;
  animation-play-state: paused;
  animation-fill-mode: forwards;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

Now, I configured the javascript to pause/play the vinyl onClick. The problem: Once I pause & play again, the animation restarts from 0deg, and not the angle I had paused at. Is there some way for me to retain the final state of the angle and use that to rotate again?

I tried making 2 animations (paused and replayed) but it won't work because I have no way of knowing what angle I end at. I also attempted the animation-direction: forwards method but it does not work either.

Here is my javascript file:

import React, {useState} from 'react'

const AlternateVinyl = () => {

    const[isPlaying, setIsPlaying] = useState(false);
    const[wasPlaying, setWasPlaying] = useState(false);

    const handleClick = () => {
        setWasPlaying(isPlaying);
        setIsPlaying(!isPlaying);
    }

    function animationState(isPlaying, wasPlaying){
        if (isPlaying == wasPlaying){
            return '-stationary';
        }
        else if(isPlaying){
            return '-playing';
        }
        else{
            return '-paused';
        }

    }

  return (
    <div>
    <div className='vinyl-container'>
        <div className='vinyl-turntable'>
            <img className={`vinyl-record${animationState(isPlaying, wasPlaying)}`} src='/plain-vinyl-square.png' alt='vinyl record' onClick={handleClick} />
        </div>
    </div>
</div>
  )
}

export default AlternateVinyl

Here is my component wrapper:

import './App.css';
import Vinyl from './Vinyl';
import AlternateVinyl from './AlternateVinyl';

function App() {
  return (
    <div className="App">
      <AlternateVinyl />
    </div>
  );
}

export default App;

This is my plain-vinyl-square.png image

Upvotes: 0

Views: 34

Answers (0)

Related Questions