Episode 13: Animating Color
If you want to easily create animations in jQuery, you can use the
animate() method to animate any numerical CSS property –
top, etc. However, even though colors in CSS are technically numerical, the jQuery
animate() method won’t animate colors.
The jQuery team released the jQuery Color plugin which adds support for color animation, but with CSS3 and the transition property, we don’t even need the plugin to create color animations. We can use jQuery in combination with CSS for animating color without using the Color plugin.
We get started by creating a simple grayscale style for a
<div>. Then we add a hover style to the
<div> to show how we can use CSS to change the color scheme of our
<div> on hover using just CSS. It’s okay, but it’s just a sudden color change.
So we take a look at how we can use the CSS
transition property to create an animation for that color change. All we have to do is add the transition property to the grayscale styling for our
<div>. We specify which property or properties we want to add an animated transition to, then we say how long the animation should take to complete. You can get even more specific about your transition, so check out this article for more information on what you can do.
CSS alone works great as long as we only want the animation to happen when we’re hovering, but if we want to animate the color change on click, we have to step into using a bit of jQuery. We can use a CSS class in combination with a click event handling function to animate the color change when we click. All we have to do is use jQuery’s
addClass method to add the class.
And if we want to toggle the class on and off, we can just use jQuery’s
toggleClass method instead. We take a look at how we can use different color schemes for each individual
<div> so that each changes to a different color when clicked.
No comments yet.