Controlling CSS3 animations using jQuery – Simple Loveliness

The introduction of CSS3 based animations afew years ago really got me excited. No longer did we have to rely on jQuery .animate() to add so visual candy to our websites as we could now do it directly in our stylesheet. When first introduced, CSS3 animations wasn’t widely supported by most browsers but today Chrome, Firefox, Safari and even IE 9 provide fantastic support.
My only real gripe with CSS3 animations was not being able to control the timings / trigger points of animations unless interacting directly with that element.

So…a happy middle ground i have started to use alot more often to let CSS3 control the animations side and use jQuery to control / trigger the animations. This is great when you want to animate element when you interact with a separate element. Say you have a button, and you want an element below to grow in height and wide when you hover on it. You could use jQuery to add an ‘animation’ class to the element when the button is hovered over like this –

$("#button").hover(
	function () {
	$('#myelement').addClass('animate');
	},
	function () {
	$('#myelement').removeClass('animate');
	}
      );

This simple snippet of jQuery basically adds your ‘animate’ class to the desired element when hovering over the button and removes the class when the cursor leaves. Your ‘animate’ class might look something like this –

.animate{
     transition: all 0.7s ;
     width:400px;
     height:200px;
}

This class states that the animation transition should affect all properties and last 0.7 seconds. The properties we have chosen to animate are the height and width.

Leave a comment