user4175297 user4175297 - 1 month ago 7
CSS Question

Trigger same CSS animation on every click

I'm trying to trigger a CSS animation onclick, but have it restart after each click. I know I can toggle the animation on and off, but I'd like to just trigger the animation every time the button is clicked. Also, initially the CSS animation should not run. Only run when clicked.

Here's my pen.
http://codepen.io/omarel/pen/JRwpZp

HTML :

<a href="#" class="addtocart">click me</a>


Jquery :

$('.addtocart').click(function () {
$(this).addClass('on');
});


CSS :

.addtocart {
position: relative;
}

.addtocart.on {
-webkit-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
-moz-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
-ms-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
-o-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
}

@keyframes cartbtnFade {
0% {
opacity: 0;
transform: translateY(-100%);
}

10% {
transform: translateY(-100%);
}

15% {
transform: translateY(0);
}

30% {
transform: translateY(-50%);
}

40% {
transform: translateY(0%);
}

100% {
opacity: 1;
}
}

Answer

You can listen to when the animation ends, then remove the class 'on'

var animationEvent = 'webkitAnimationEnd oanimationend msAnimationEnd animationend';
$('.addtocart').click(function () { 
  $(this).addClass('on');
  $(this).one(animationEvent, function(event) {
    $(this).removeClass('on')
  });
}); 

$('.addtocart').click(function () { 
  $(this).addClass('on');
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(event) {
    $(this).removeClass('on')
  });
}); 
.addtocart {
		position:relative;
  width:100px;
  display:block;
  background-color:#000;
  color:#fff;
  padding:10px;
  text-align:center;
	}
	.addtocart.on {
    -webkit-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -moz-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -ms-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    -o-animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
    animation: cartbtnFade 0.6s 0.1s 1 linear alternate;
	}

@keyframes cartbtnFade {
  0% {
    opacity: 0;
    transform:translateY(-100%);
  }
  10% {
  	transform:translateY(-100%);

  }
  15% {
	  transform:translateY(0);
	}
	30% {
	  transform:translateY(-50%);
	  
	}
	40% {
	  	transform:translateY(0%);

	}
  100% {
    opacity: 1;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="addtocart">click me</a>