javascriptcsstypescriptcss-animationskeyframe

CSS animations cycle doesn't work as it should


I have created two classes for two animations that pressing a button should turn fullscreen on and off using one animation first and another one after a second press of the button.

CSS Animate enable fullscreen, animatereverse disable it

    #mv {
        width: 100%;
        height: 57%;
    }

    .animate {
        animation: fullscreen 0.5s;
        animation-fill-mode: forwards;
    }

    @keyframes fullscreen {
        from {
            height: 57%;
        }

        to {
            height: 100%;
        }
    }


    .animatereverse {
        animation: fullscreenreverse 0.5s;
        animation-fill-mode: forwards;
    }

    @keyframes fullscreenreverse {
        from {
            height: 100%;
        }

        to {
            height: 57%;
        }
    }

TS/JS I used a flag to make the function know if the interface is in fullscreen or not

      var fullscreen = false;
      //console.log(" fullscreen now false ");
        document.getElementById('fllbtn').addEventListener("click", function () {          
          if(fullscreen == false){     
            //console.log(" fullscreen is false ");
            fullscreen = true;
            //console.log(" fullscreen now true ");
            document.getElementById("mv").classList.toggle("animate");
          }else{
            //console.log(" fullscreen is true ");
            fullscreen = false;
            //console.log(" fullscreen now false ");
            document.getElementById("mv").classList.toggle("animatereverse");
          }
        })

The problem is as follows:

BEGIN
*non-fullscreen interface
*I press fullscreen button
*animation works, interface becomes fullscreen
*I press fullscreen button
*animation works, interface returns to initial non-fullscreen state
*I press fullscreen button
*animation does not work, does not go fullscreen
*I press the fullscreen button
*animation does not work, does not go to fullscreen
END

Think of it as a loop, it basically runs twice, jumps twice and repeats like this.


Solution

  • I found a better way, I simply use a transition:

    CSS

    #mv {
        width: 100%;
        height: 57%;
        transition: height 0.5s ease;
    }
    
    #mv.fullscreen {
        height: 100%;
    }
    

    TS/JS

      document.getElementById('fllbtn').addEventListener("click", function () {
        document.getElementById("mv").classList.toggle("fullscreen");
      })