Home > Enterprise >  How to flip image in jquery if the animation is at 0% and 50%?
How to flip image in jquery if the animation is at 0% and 50%?

Time:12-02

I am try to make a running santa in my project.

How to loop transform: scaleX(1) and transform: scaleX(-1) when the animation start in 0% an 50%?

setTimeout(function(){
  //Enter your stuff here
  $('.animation').css("transform", "scaleX(1)")
}, 7500);  
.animation img {
  max-width: 100%;
}

.animation {
  width: 50px;
  position: absolute;
  bottom: 0;
  animation: example 15s infinite; 
  padding: 5px 9px 1px 0;
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  transform: scaleX(-1)
}

@keyframes example {
  0%,
  100% {
    left: 0;  
    /* background: white; */
  }
  40% {
    /* background: green; */
  }
  30% {
    /* background: yellow; */
  }
  20% {
    /* background: orange; */
  }
  50% {
    left: 97%;  
    /* background: blue; */
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation">
  <img src="https://lh3.googleusercontent.com/pw/AM-JKLX6lpuXIUQzWYC8J9vlnsS9Cb9irs-2kPKBM9XaugC4iDCag2-7w-zC7BSQls0Ea51YewUFFSJquODLZ8PfaAoqelAXOlCKmh0H7Cn9G5HcwX_u2XNT_tvr8ZD5as6He3dpMrrVH_-ZCaG1xctS_Tei=s512-no" alt="run santa run">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Codepen link: demo

CodePudding user response:

it is a good practise.

I tried to use JS/Jquery listener to solve it but it might be difficult cause we need to track the keyFrame changes instead of just start/end point.

So I am thinking to solve it via CSS only. Your requirement is to flip the santa when it hits the viewport. If we just set transform: scaleX(1) at 50%, then the santa will flip at halfway.

Therefore I set mark point at 1%, 49% and 99% to make sure santa will not flip at these point. Below is my code based on your codepen link:

 @keyframes example {
    0%,
    100% {      
      transform: scaleX(-1)
        /* background: white; */
    }
  1%{
    left:1%;
    transform: scaleX(-1);
  }
  99%{
    left:1%;
    transform: scaleX(1);
  }
    40% {
        /* background: green; */
    }
    30% {
        /* background: yellow; */
    }
    20% {
        /* background: orange; */
    }
  49% {
    left:96%;
    transform: scaleX(-1)
  }
    50% {
      transform: scaleX(1);
        /* background: blue; */
    }  
}
  • Related