Search code examples
javascripthtmlcsswebcss-animations

Why My CSS animation is not working in Javascript


I am trying to animate my Cube(dice) when user presses the button and execute dice case. My Code works perfect but animation does not work. I am using timeout but it's not working.

HTML

Cube is dice, Side is sides of the cube

<div class="cube">
        <div class="side top"></div>
        <div class="side bottom"></div>
        <div class="side front"></div>
        <div class="side back"></div>
        <div class="side right"></div>
        <div class="side left"></div>
    </div>
    <input type="submit" value="Roll" id="roll">

CSS

.cube
{
    position: relative;
    width: 100px;
    height: 100px;
    transform-style: preserve-3d;
    transform: rotateX(193deg) rotateY(269deg);
    animation: rolling 4s;
}
.anim {
    animation: rolling 3s;
}
@keyframes rolling {
    50% {
        transform: rotateX(455deg) rotateY(455deg);
    }
    
}

JS

document.getElementById("roll").addEventListener("click", function () {
    side = Math.floor(Math.random() * 6);
    console.log(`dic Case : ${side}`);
    document.getElementsByClassName("cube")[0].classList.add("anim");
    setTimeout(() => {
        roll(side);
    }, 4000);
})

Also, If you can also improve some of the design in my CSS please do so


Solution

  • You can use this code.

    css code

    .cube {
      position: relative;
      width: 100px;
      height: 100px;
      transform-style: preserve-3d;
      background-color: red;
    }
    
    .anim {
      animation: rolling 3s;
    }
    
    @keyframes rolling {
      50% {
        transform: rotateX(455deg) rotateY(455deg);
      }
    
    }
    

    javaScript code

    document.getElementById("roll").addEventListener("click", function () {
      side = Math.floor(Math.random() * 6);
      console.log(`dic Case : ${side}`);
      document.getElementsByClassName("cube")[0].classList.add("anim");
      setTimeout(() => {
        document.getElementsByClassName("cube")[0].classList.remove('anim')
      }, 3000);
    })