Here’s a demo.
Using CSS3 transforms, web page animation can be tricky especially when hooking up to click/change events. Sure you can do this through pure CSS but the closest you can get is :active. This is limited since it only applies the style when the mouse button is held down. The only way to apply a style and keep it applied onclick is to use a bit of JavaScript.
I have this bounce effect CSS3 animation.
.bounce{
animation-name: bounce;
animation-duration: 0.5s;
animation-fill-mode: both;
transform-origin: center bottom;
}
@keyframes bounce {
from, 20%, 53%, 80%, to {
animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transform: translate3d(0,0,0);
}
40%, 43% {
animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transform: translate3d(0, -30px, 0);
}
70% {
animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transform: translate3d(0, -15px, 0);
}
90% {
transform: translate3d(0,-4px,0);
}
}
As you noticed, the “bounce” class will animate the element on page load. Using jQuery, let’s write a function that will apply the “bounce” class dynamically to an element.
var animate = function(element_to_animate,animation){
element_to_animate.removeClass().addClass(animation).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
};
The animate function needs 2 parameters to work correctly. The first is the jQuery DOM object to animate and the second one is obviously the class name in our CSS that triggers animation. However, the main trick here is to attach a handler that removes the animation (bounce) class as soon as animation ends. Since animation is an asynchronous event, I’m using jQuery’s API (one) to attach the handler as soon as animation stops.
And now to use the animate function on the click event.
var element_to_animate = $('.panel h2');
$('.btn').click(function(){
animate(element_to_animate,'bounce');
});
Check-out the demo.