skip to Main Content

I’m using a simple css animation and by clicking on a button I toggle class and playing animation reverse.
Unfortunately the animation play correctly on loading page but when i click on the button the animation don’t run it give me the last keyframe without any animation and delay.

<div>
  <button>click</button>
  <span ></span>
</div>

span{display:block;width:100px;height:100px;}

@keyframes a{
from { background:red;}
to {background:lime;}
}


.opened{
  animation:a 1s;
  animation-direction:reverse;
  animation-fill-mode:forwards;
  animation-delay:3s;
}
span{
  animation:a 1s;
  animation-fill-mode:forwards;
  animation-delay:3s;
}

$("button").click(function(){
  $("span").toggleClass("opened");
});

Here is my code pen example code pen

2

Answers


  1. Chosen as BEST ANSWER

    I try to better explain what I'm trying to achieve. I have a collapsible menu, when this is closed it must be position:static, when opened must be position:fixed, by closing it it will return to static position but after a delay time to let some animation been played before it will closed.

    I achieved this on my code pen

    div{width:100px;height:100px;}
    
    @keyframes a{
    from { background:red;position:fixed;}
    to {background:lime;position:static;}
    }
    
    .opened{
      animation:unset;
      position:fixed;
      background:red;
      border-right:5px solid green;
    }
    div{
      background:red;
      position:fixed;
      animation:a 1s;
        animation-delay:3s;
        animation-fill-mode:forwards;
    }
    

    but I don't know why on my website the background style works good but it keeps the fixed position: https://www.jcprod.it/


  2. add jquery cdn and place your jquery code inside $(document).ready();

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("button").click(function () {
                    $("span").toggleClass("opened");
                });
            });
           
        </script>
    

    if above is proper then you can modify css class like below:

    .opened {
              animation:unset;
              /*animation: a 1s;
              animation-direction: reverse;
              animation-fill-mode: forwards;
              animation-delay: 3s;*/
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search