Thursday, May 31, 2012

Animating a List with CSS3 Transitions

As I've been exploring all the cool features of CSS3, I've been trying to keep in mind cool ways to put them to use. CSS3 Transitions are so sweet and so easy that they can really make for much richer and interactive web sites with hardly any effort. And when a browser doesn't support it, it's not that big of a deal -- the elements still end up getting the correct properties... the user just doesn't see the animation.

I wanted to see how CSS3 transitions could be used for animating a sortable list. In this case, I've got a leaderboard for a video game competition. Let's see who's winning at the moment...

  • Rank

I think this is a pretty groovy use of CSS3 transitions. Most of the time when we're sorting a list, it's in response to a user's action. For example, if he's looking at an email list and clicks on the Subject field header, he's expecting the list to sort by subject.

But in the case of the leaderboard, the list is resorting without input from him, so it's harder for him to naturally figure out what just changed when the board was updated. We make this easier for the user by giving him a one second transition, so that he can visually see the player who just moved up and down in the ranks. Sweet!

Show me the code!

The full code for this demo is a bit verbose, especially when including all the styles that are just there to make it look nice. But here's the, er... gist... of it.

Every time the scores are updated, the players array is sorted again by score. Then we call the reposition method, which loops over the players array and sets the top property on each player list item. The simple transition-duration property does the rest of the magic for us.

Not bad, but the fact that you have to use absolute positioning on those list items makes it a bit of a bear. Still, it's quite a helpful effect, and the actual transition part of it is so doggone simple!

Speak up!

How have you used CSS transitions to spice up your site?

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile