Chad Upton

Animating CSS Properties with jQuery

By Chad Upton - senior consultant

jQuery is a seemingly endless tool for making advanced tasks easy and cross browser compatible. One of those tasks is animation, and jQuery is great at it.

For example, lets say we’re building a shopping cart application and we’d like to grow and shrink a product image when a user clicks on it. Here’s the HTML tag for the image:

<img id='logo' src='logo.gif'/>

In JavaScript, we’ll target the image with jQuery syntax:

$('#logo')

Next, we’ll add a toggle event handler. Toggle on its own will simply show/hide something, but we can add extra handlers for more advanced functionality. Here, we’ll add two methods that will be called alternatly each time the logo is clicked

$('#logo').toggle(function() {
}, function() {
});

Inside each of those functions, we’ll specify the property we want to animate. In this case, we’ll use the image’s height. We want it to grow by 100 pixels and we want that animation to take approximately 400 milliseconds to complete. The alternate function will shrink the image by 100 pixels over 400 milliseconds.

$(document).ready(function(){
$('#logo').toggle(function() {
$(this).animate( {height:'+=100px'}, 400, 'swing');
}, function() {
$(this).animate( {height:'-=100px'}, 400, 'linear');
});
});

I’ve also added “swing” and “linear” easing to these animations. If you’re not familiar with easing, it can make animations look more fluid by changing the acceleration of the animation at the beginning and the end. Linear easing offers no change in acceleration while swing offers a slight change. The difference is subtle, but you can see it if you look closely.

I published the working code to jsfiddle, click here to try it out.

 

 

Share

Tags: , , , , , , , ,

Leave a Reply