Monday, October 26, 2015

Animate Colors with jQuery

While working on an upcoming comic, I wanted to add a color-change effect to an element. I soon learned that jQuery's animate() function doesn't support animation of non-numeric CSS properties. So while I can animate a width between 100px and 200px, for example, I can't animate a color between #000000 and #FF00FF.

But all is not lost! There is a plugin, appropriately named jQuery Color, which adds the color animation feature. It is trivial to use and extremely small to download.

To start using it, just download the .js file from their GitHub page. I am using the minified version. Include it in your page after jQuery. Then, just animate colors the same way you would animate other CSS properties and it will magically work!

In the following example, the page starts out containing a DIV with a black background. As soon as jQuery is ready, an animation changes the background color to purple over a span of 10 seconds.

<!doctype html>

<html lang="en">
  <meta charset="utf-8">
  <title>Color Animation</title>


  <div id="test-div" style="width: 500px; height: 300px; background-color: #000000;"></div>


<script src=""></script>
<script src=""></script>

$(function() {

    $('#test-div').animate({backgroundColor: '#FF00FF'}, 10000);




It doesn't get much easier than that! But what comic prompted me to use this? It's not for today's. You'll just have to wait to find out (or look in the repository on GitHub). comic for 26 October 2015

No comments:

Post a Comment