Neil Neil - 23 days ago 11
CSS Question

Highlight Animation Only Works Every Other Time the Button is Clicked

When the

button
is clicked: the
div
element is highlighted green, and then the green fades away.

It works, but it only works every other time.


  • The 1st, 3rd, 5th... time you click the button the animation occurs.

  • The 2nd, 4th, 6th... time you click the button the animation does not occur.



Question: How can I make the animation occur every time the button is clicked?



$('button').on('click', function(){
$('div').toggleClass("success-highlight-animation");
});

/*********************************************/
/*********************************************/
/* Fades in success color, then fades it out */
.success-highlight-animation {
-moz-animation: highlight 2s ease 0s 1 alternate ;
-webkit-animation: highlight 2s ease 0s 1 alternate;
animation: highlight 2s ease 0s 1 alternate;
}

@-webkit-keyframes highlight {
from { background-color: #dff0d8;}
to {background-color: white;}
}

@-moz-keyframes highlight {
from { background-color: #dff0d8;}
to {background-color: white;}
}
// end .success-highlight-animation
/*********************************************/
/*********************************************/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>click</button>


<div>
When the button is clicked this shows a highlight that slowly fades away.
</div>




Answer

It's because the 2nd, 4th, etc. times are removing the css class. 1st, 3rd, etc. are adding it. You need remove the class in your function once the animation is finished.

$('button').on('click', function(){
  setTimeout(function() {
    $('div').removeClass("success-highlight-animation");
  }, 2000);
  $('div').addClass("success-highlight-animation");
});
/*********************************************/
/*********************************************/
/* Fades in success color, then fades it out */
.success-highlight-animation {
  -moz-animation: highlight 2s ease 0s 1 alternate ;
  -webkit-animation: highlight 2s ease 0s 1 alternate;
  animation: highlight 2s ease 0s 1 alternate;
}

@-webkit-keyframes highlight {
  from { background-color: #dff0d8;}
  to {background-color: white;}
}

@-moz-keyframes highlight {
  from { background-color: #dff0d8;}
  to {background-color: white;}
}
// end .success-highlight-animation
/*********************************************/
/*********************************************/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <button>click</button>


<div>
  When the button is clicked this shows a highlight that slowly fades away.
</div>