Home > Mobile >  JQuery animation chining
JQuery animation chining

Time:06-18

Greetings as stated in the title i am unable to chain multiple jQuery animation.

I need to use switchClass function to progressively toggle bootstrap classes with a specific timing to build up my animation. I would premit that i found strange this error, because i rememer that the function worked as intended few week ago. Here the code i had used :

$(button).switchClass("btn-primary", "btn-warning", 800)
$(button).switchClass("btn-warning", "btn-success", 800)
$(button).switchClass("btn-success", "btn-primary", 800);

Here a jFiddle with a minimal example of my scenario, in which i the animation does not work anymore :

https://jsfiddle.net/s6uxaLzt

So my question is, how can i execute the transition (switchClass) in the order described above?

CodePudding user response:

Given your description of the goal, it appears you're attempting to have the background-color of the button element fadde between the different colours. Switching classes through JS is not an ideal way of doing that.

A better approach would be to use CSS to animate the colour changes using @keyframes. It would look something like this:

$('button').on('click', e => {
  $(e.currentTarget).addClass('animate');
}).on('animationend', e => {
  $(e.target).removeClass('animate');
});
body button.btn.btn-primary:focus {
  outline: 0;
  box-shadow: none;
}

button.animate {
  animation: background-fade 2.4s;    
}

@keyframes background-fade {
  0% { 
    background-color: #007bff; 
    border-color: #007bff; 
  }
  33% { 
    background-color: #ffc107; 
    border-color: #ffc107; 
  }
  66% { 
    background-color: #28a745; 
    border-color: #28a745; 
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<p>Click the button to see the colour fade animation:</p>
<div >
  <button  type="button">
    <span >Animate</span>
    <span  role="status" aria-hidden="true" style="display:none;"></span>
  </button>
</div>

  • Related