Search code examples
javascripthtmlcssrotationkeyframe

How do I stop and change a CSS keyframe in Javascript?


I made a keyframe in my CSS which rotates a IMG in HTML. Now, I want to make a button that changes the rotation of the IMG from Y to X.

CSS:
  */* Rotate IMG Y */
@keyframes rotate {
    0%       {transform: rotateY(0deg);}
    100%     {transform: rotateY(360deg);}
  }
  /* ROTATE IMG X */
  @keyframe rotateOther {
    0%      {transform: rotateX(0deg);}
    100%    {transform: rotateX(360deg);}
  }*

I basically want to change ROTATE IMG Y to ROTATE IMG X by pressing a button. I am kind of new to programming and could not find any good explanation how to do this.


Solution

  • use insert class to change the css of div

    <!DOCTYPE html>
        <html>
        <head>
        <style>
        div {
            width: 200px;
            height: 100px;
            background-color: yellow;
          animation: rotate 5s 1;
           /* transform: rotate;*/
        }
    
        @keyframes rotate {
            0%       {transform: rotateY(0deg);}
            100%     {transform: rotateY(360deg);}
          }
    
        .newstyle{
         background-color: green;
          animation: btnrotate 5s 1;
        }
    
        @keyframes btnrotate{
            0%       {transform: rotateX(360deg);}
            100%     {transform: rotateX(0deg);}
          }
    
        </style>
        </head>
        <body>
    
        <div id="mydiv">Hello</div>  <button type="button" id="rotate" onclick="myfun(event)" > rotate </button>
        <br>
    
    
    
    
        <script>
        function myfun(event){
          event.preventDefault();
        console.log(event);
        document.getElementById("mydiv").classList.add("newstyle");
    
        };
        </script>
        </body>
        </html>