Amit Dhamu

Writes Code

Control CSS3 Animations With jQuery

With the momentum that CSS3 is gaining on the web, there are some really cool looking sites out there which deliver smooth native animation to the user. This guide explores how to control your CSS animations with jQuery.

I'm not going to be using vendor prefixes in this guide so add these when you need them. There is a basic introduction to CSS3 animations here.
Our Animation Function

@keyframes "TestAnimation" {
    0% {
        width: 500px;
    }
    50% {
        width: 800px;
    }
    100% {
        width: 500px;
    }
}


Add Function To Class

.animate-me {
    animation-name: TestAnimation;
    animation-duration: 5s;
}


Now let's say that on a button click, I want an element to animate. To do this, we need to add the .animate-me class to an element, show the animation and then remove the class ready for the next time our button is clicked.

HTML

// Our button
<input id="button" type="button" onclick="toggleAnimation()"/>

// Image we want to animate
<img src="photo.jpg" alt=""/>


jQuery

function toggleAnimation() {
    var animationClass = '.animate-me';
    // Listens for when the animation completes and removes the animation class as a result
    $('img').bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function (e) {
        $(this).removeClass(animationClass);
    });
    // Adds the animation class and in doing so animates our image
    $('img').addClass(animationClass);
}


This is a very simple example but demonstrates the point.
I recommend downloading DanEden's animate.css which is basically a bucket load of cool CSS animations that you can tweak to your liking and incorporate into your site.


animation / css3 / transitions / jquery

← New Design F1 Result Finder Web Application →