This lightweight JavaScript allows for easy color transitions. Add fading effects to tables, divs and more. You can target an elements background, border or text color.

Below is the command to call the function.

colorFade('divid', 'background', 'ece7b4', 'f9bcbc', 25, 30)

The first parameter is the id of the element you are targeting. The second is the property to fade which can be the background, border or text. The third is the hex value of the starting color. The third is the hex value to fade to. The fourth and fifth are both optional. The first is the the number of times to divide the color difference and the last is the transition speed.

This script has been tested in all major browsers and is available free of charge for both personal or commercial projects under the creative commons license. Community support is available here. Paid support is also available, contact me for details.

Click here to view the demo.

Click here to download the script.

Update 5/5/2008 – I have tweaked a few things and integrated some performance improvements based on Nate’s suggestions.

Posted by Michael in Design,JavaScript on May 2, 2008

81 Responses

Thanks! How would you make this work on page load? So that the color would fade as soon as the page loaded?

Zac on May 03, 2008 at 11:16 am

@Zac – Something like this should do the trick… you can view it at http://sandbox.leigeber.com/fader/fader3.html.

<body id=”sitebody” onload=”colorFade(‘sitebody’,'background’,'ffffff’,'cde8ae’,25,30)”>

Michael on May 03, 2008 at 11:49 am

Thats a very nifty trick, its actually smoother then jquery. Nice work.

Web Development Blog on May 04, 2008 at 12:52 am

How can I do an automatic fade to two colors, I mean the div changes from black border to red?, and when the div changes to red, then it change again to black. Thanks

Mario on May 04, 2008 at 7:49 pm

@Mario – You would need to extend the colorFade function to take a third hex color, pass that variable to the animateColor, and then after line 65 in the else statement call the colorFade function again. Shoot me an email if you need any help figuring it out.

Michael on May 04, 2008 at 8:01 pm

very sweet! I was just looking for something like this. thanks!!

Shanna on May 04, 2008 at 8:38 pm

Nice trick, also have a look at colorBlend plugin for jQuery which is really powerfull.

http://www.happinessinmycheeks.com/colorBlend/

Zero1infintiy on May 05, 2008 at 5:56 am

This works great, but I looked over the code and have a few suggestions to tighten it. What you have now is fine… just pointing out a couple of things I’ve picked up over the last few months, writing this kind of stuff.

eval() slows things down, and can be avoided in pretty much any situation.

You can get rid of your decConv function. Just replace it with:
parseInt(“[2 digit hex]“, 16);
//parseInt’s second parameter is the base, and default to base 8 if the first character is a “0″

This should also make your colorConv function much simpler. You could rewrite it as:
function colorConv(color) {
var rgb = [
parseInt(color.substring(0,2), 16),
parseInt(color.substring(2,4), 16),
parseInt(color.substring(4,6), 16)
];
return rgb;
}

setInterval can take an anonymous function instead of the eval’d string you currently pass, which also makes it easier to read/maintain:
target.timer = setInterval( function() {animateColor(id,element,steps,er,eg,eb,rint,gint,bint);}, speed);

Another little trick is to define undefined variables with ||
You could use the following:
steps = steps || 20;
speed = speed || 20;

You could also scope all functions inside of the colorFade function. This will make it so you only introduce 1 variable into the global namespace.

Nate on May 05, 2008 at 9:00 am

@Nate – Some really good suggestions there. I will look through my code and work in these and a couple other little things I noticed yesterday. Thanks for the tips.

Michael on May 05, 2008 at 9:15 am

PERFECT TIMING! I’d visualized a fade-in a couple weeks ago. You posted this code on May 2 and modified on May 5. And I went lookin for code samples today, May 6. Lucky me.

I’ve applied your code via <body onload= … and it’s almost exactly what I need. The only enhancement I’d suggest is a “delay” parameter before the fader starts.

Thanks,
Richard

RP on May 06, 2008 at 2:25 pm

Is there anyway of putting the onmouseover and onmouseout in a javascript in the hedear, so you are left with a clean div?

<head>
<some java script that applies for someID>
</head>
<div id=”someID” class=”darkgrey”>Third Div</div>

Would be really grateful if you can mail me the solution, if there is one.

thanx alot
hamochi@gmail.com

hamochi on May 06, 2008 at 7:07 pm

@hamochi – Absolutely, I definitely recommend adding events dynamically. I wrote an article recently pointing that out. I would recommend not adding the JavaScript in the header but rather keep it all external. Plus if you try adding these events in the header you will get an error. You could add the events before the </body> if you have to must. You can add mouse events like the following…

document.getElementById(‘id’).onmouseover = function() { whatever };
document.getElementById(‘id’).onmouseout = function() { whatever };

Michael on May 06, 2008 at 8:39 pm

Hey, awesome script! I am loving it!
One thing I am wondering about, I have the script tied in with AJAX and the DIV fades when updated, which works great. But after the initial fade, mouseover, mouseout, and the update fade that originally worked, does not.

Is there a “reset” that I am missing? The update fade is called at page load, and if it happens, the fade no longer works.

Again, awesome work. :)

Curt on May 30, 2008 at 12:52 pm

@Curt – Shoot me an email and I will take a look. Want to make sure I am following you correctly.

Michael on May 30, 2008 at 12:58 pm

Heya, have a look at this script, it combines changing colours and sliding at the same time. Think it might be somthing similar to this: http://www.whadiz.com/c/whatis.aspx/programming/javascript/javascript_slide_fade_marquee

Ryan on June 05, 2008 at 2:25 pm

I noticed that if you try to call this via a function or some other automatic (read: no human interaction required) it doesn’t do any fades past the first one. However, if you call it with an event (like onmouseover) then it works flawlessly. Go figure.

Marcus on June 09, 2008 at 5:55 pm

OK, my fix for this was to store the timer and r,g,b in an object instead of directly on the element. Worked like a charm

Marcus on June 09, 2008 at 6:27 pm

This is by far one of the cleanest and browser friendly scripts I have come across. If you had a donation option on this site, I’d gladly contribute towards your work.

TGLS on June 12, 2008 at 8:14 am

@TGLS – I really appreciate the offer, I may get around to adding a donation button sometime but in the meantime your appreciation means just as much to me. Thank you.

Michael on June 12, 2008 at 8:22 am

Is there any way I can use it for li tag?
I think this will be good for menu item which uses li tag.

Thanks another great script.

elvis on June 16, 2008 at 2:38 am

@elvis – You should be able to use it for list elements as-is. If you are having a problem for some reason shoot me a message.

Michael on June 16, 2008 at 10:33 am

This is great! It works great on regular text, but how do I get it to work on links? thanks!

mcd on June 19, 2008 at 11:47 am

@mcd – Take a look at the demo page, I added a link at the bottom that demonstrates. Just call the function as it is used in the font color transition section except on an a tag and not a div.

Michael on June 19, 2008 at 12:34 pm

Regarding Curt’s issue, the problem happens because of the conditional:

if(!target.r) { … }

If the function runs a second time on the same element, it finds the old “r” and it messes up. Commenting out the conditional (but not the code inside) resolves the issue.

Michael, what is the purpose of that line of code?

Kurt on June 22, 2008 at 12:57 pm

@Kurt – That function was only in place to eliminate the RGB from being calculated again again if it already existed. It is no big deal to remove that statement, not a huge overhead.

Michael on June 22, 2008 at 1:20 pm

I appreciate the work you have done. It has helped me tremendously! I used this fade function with a transparent background function and it looks great. However, I’m having an issue with a bit of flicker and was curious what you thought it might be. Here is the site: http://www.yachtpartnership.org/yacht_preview.html
I’ve left all the JAVA and CSS in the HTML in order to show you.

Parker on June 25, 2008 at 7:47 pm

I had the same problem as a couple here where the fade only works the first time. (fixed)

Problem can be seen on the link posted by someone else earlier
http://sandbox.leigeber.com/fader/fader3.html
If you hit one of the DIV links it works, but if you hit the same link again the fade does not happen again, you have to reload the page.

Not knowing exactly why in the colorFade funtion there is a “if(!target.r)” I did a workaround. I added “target.r=0;” efter the else clause in animateColor function.

—–cut——
} else {
clearInterval(target.timer);
target.r=0;
color = ‘rgb(‘ + er + ‘,’ + eg + ‘,’ + eb + ‘)’;
—–cut——

The thing is that the START color is not set for any additional hits to the funtion, so “startrgb” is undefined and the fade does not know what color to start with and ends up starting around the existing color (which is what the last fade ended on)

hope this helps someone

Palle Nielsen on June 30, 2008 at 10:50 am

thanks! small but cool implementation http://redseacheck.com

roger   on July 17, 2008 at 8:34 am

he he ;) i love the simplicity of this and playing around with it amazing how disappearing links can bring a smile to your face ;) http://eti.me

roger   on July 19, 2008 at 6:17 am

Thank you so much! This is incredibly useful and well written.

JG on July 23, 2008 at 7:25 am

Hi, this is a very nice script.

I would like to use this on a div that allready has a background image (transient) so I was wondering if it is possible to start and end with a opacity of 0 (transparent)

Michael on July 30, 2008 at 5:04 am

he,a great js you did but get a problem.
how to use it in table?
too much <tr> to add onmouse event on it.
could you give a demo that solute by loop?
and I quite like the js ,useful.

mimi on August 09, 2008 at 10:21 pm

@Parker – Sorry just getting to your comment. The link is down but if you get me an updated link I will look into it.

@Palle – Thanks for sharing.

@Michael – It depends on what you are trying to fade… not fully understanding your request.

Michael on August 12, 2008 at 8:24 pm

would it be possible to fade images instead of colors? thanks!

LP on August 28, 2008 at 12:25 pm

Hey, awesome script. Simple and useful. Thanks for the new trick. Have you explored a way to use the function on multiple properties for the same element? I’ve tried a code like:
… colorFader(‘div1′,’background’,’000000′,000011′);
colorFader(‘div1′,’text’,’445566′,’112233′);…
for example and only the second call has an effect. Any thoughts?

Jesse

Jesse on September 17, 2008 at 2:08 pm

@Michael – What a great script. It’s people like you that make the web go round.
@Jesse – That was the first thing that came to my mind I wanted to realise. Great for a decent button. Sadly I also haven’t figured it out how to get 2 properties working on one ID. Maybe help is on the way from a more expierienced Javascripter.

-Patte

patte on September 25, 2008 at 11:04 am

This is a great snippet of code. Do you have any licence information associated with using this code? e.g. a MIT, Apache or GPL licence?

Thanks
Dan

Daniel Harrison on November 11, 2008 at 3:56 am

This is a great piece of code but it only works once for me. I am building a site that has tabulated data, in each cell are icons, one of which if you click shows the full cell data in another div (the data is truncated in the cells). I’m using your color fade to draw attention to that div, fading it from a red to the background color so the user can see where the information is.

Click one of the icons in a cell and it runs. Click any other icon after that and nothing happens. I haven’t debugged yet but was just curious if you’ve seen this happen in other situations.

Thanks again for the cool code.

Steve on November 12, 2008 at 1:13 pm

I’m actually having the same issue as Steve…does a timer need to be reset or something? Sorry, not experienced with js…

Chad on November 18, 2008 at 3:55 pm

@Steve: I read through the postings above and found the answer:

Regarding Curt’s issue, the problem happens because of the conditional:

if(!target.r) { … }

If the function runs a second time on the same element, it finds the old “r” and it messes up. Commenting out the conditional (but not the code inside) resolves the issue.

Michael, what is the purpose of that line of code?
Kurt on 22 Jun 2008 at 12:57 pm

@Kurt – That function was only in place to eliminate the RGB from being calculated again again if it already existed. It is no big deal to remove that statement, not a huge overhead.
Michael on 22 Jun 2008 at 1:20 pm

Chad on November 19, 2008 at 8:32 am

does anyone know how its possible to do these things regarding a fading background color?

1) Add another two colors to the fade.
2) Turn the fade into a loop, ie. it never stops.

thanks

conor on December 10, 2008 at 4:44 pm

This is great stuff. How can i change the background to a previous state?
at the moment i am using it as as soort overlay function on a div whit no background. on mouseover i want to change it to a nice fading color
in mouse out i want to fade it out to no color. is this possible

Michael on February 20, 2009 at 6:33 am

awesome man ….. its working very good…

tresloukadu on April 29, 2009 at 12:59 pm

I’m calling a list of links dynamically :

‘ul’ somePHP ‘/ul’

, so I have only an ‘ul’ html tag to implement the code (not the ‘li’ or the ‘a’…). There’s a way to affect the child elements -its text- ? thanks !

Jan on May 03, 2009 at 1:29 pm

Excellent script – thank you for this – I have added your site to my favorites and will be spending some time here going over what you offer – thanks again.

Ed Rooney on May 05, 2009 at 11:50 am

First of all, very nice script.

Only got a problem with some work.

<div class="block">
hello <a href="#">there</a>.
</div>

It's only changing the text and not the links. Is there an option to make this work?

With Kind Regards,

Kdonkey

Kdonkey on June 16, 2009 at 7:32 am

Excellent script – any way to apply the fade to classes instead of div id? : D

Ant on June 23, 2009 at 2:50 am

Solved it, but by applying the fade to lots of div ids:

In the header:

<script type="text/JavaScript">
<!– fade the text
function getFuncs()
{
colorFade('fade','color','30373A','688E30',10,50);
colorFade('fade2','color','30373A','688E30',20,50);
colorFade('fade3','color','30373A','688E30',30,50);
colorFade('fade4','color','30373A','688E30',40,50);
colorFade('fade5','color','30373A','688E30',50,50);
}
//–>
</script>

…and on the body tag:

<body onload= "getFuncs(); return true">

Ant on June 23, 2009 at 3:38 am

Very nice job! Excellent script! I would use Classes instead of ID´s.

Bruno Camargos on June 27, 2009 at 11:37 am

Does anyone know how this would be implemented in a flash website for hyperlinks?

Stephanie on August 10, 2009 at 5:21 pm

Im having the same problem as kdonkey I want to be able to mouseover a div and all text and links in that div fade.

skux on September 01, 2009 at 3:23 pm

So has anyone come up with a solution for fading 2 properties of the same element at once, like this?:

colorFade("nextbutton", "background", "FFFFFF", "EEF5F9", 10, 100);
colorFade("nextbutton", "color", "002E5B", "237898", 10, 100);

mrpink on September 17, 2009 at 5:55 pm

Thanks heaps for he script, its really great to see a nice clean transition.

I'm a flash designer and was wondering if it's possible to apply this script to change the bgcolor of the html page(using color variables sent from flash)?

Cheers!

Monty on September 23, 2009 at 4:54 am

hi.
great code thanks:)
works great on ids but is it possible to use the effect on classes not ids? i'm making a site which has repeating product holder divs. i'd like to implement the effect to the very same classes for several times. is it possible?

sketch on October 29, 2009 at 5:24 pm

Good tus … will apply it on my websites…

website development on November 01, 2009 at 4:24 pm

Is there a way to apply a delay before the transition begins?
thanks

david on November 25, 2009 at 9:45 am

Michael, great script, thanks for sharing.

I notice there are a few comments related to the fact that once the fade effect fires, it can't be fired again because of the if(!target.r) conditional.

Have you thought about adding any kind of native work-a-round for that? I had a thought that I figured I would through your way and see what you thought.

Generally, I would prefer to avoid something like this, but my thought was that you could add another parameter (at worst it could be optional), that would allow users to "repeat" the fade effect.

What I had in mind was…

function colorFade(id,element,start,end,steps,speed,repeat) {

speed = speed || 20;
repeat = repeat || true;
clearInterval(target.timer);

if(!target.r || repeat) {

}

}

Maybe there is something I am not thinking of that is the original reason for your implementation of if (!target.r)?

I really like the script. I fought with this issue for a long time and then it dawned on me that I should just find a canned solution and yours works great. I just added the little bit I talked about so I can repeat the effect if I want.

Thanks again!

Patrick on December 08, 2009 at 10:13 pm

David, Michael's script uses the setInterval function. Javascript also has a setTimeout function. Take a look at that to implement a delay before the transition occurs.

Patrick on December 09, 2009 at 5:32 pm

Awesome work Michael!!
small problem for me though…

<body>
<div id="resume">
</div>

<div id="sidebar">
<div class="ninja">
</div>
<div class="detailtext">
</div>
</div>

<div id="main">

<div id="nav">
<div id="portfolio" > </div>
<div id="about"> </div>
<div id="contact"> </div>

</div>

<div id="infobox">
<div class="box" onmouseover="colorFade('infobox.box','background','ffffff','d8e6ee')" onmouseout="colorFade('infobox.box','background','d8e6ee','ecf2f5',25,50)"><a href="detail1.html"><img src="images/pic1.png" width="250" height="125" align="right";/></a>
<h5><a href="detail1.html">Title</a> </h5>
</div>
</div>
</div>
</body>

Viv on December 31, 2009 at 7:55 am

thanks you very much! :)

chris on January 09, 2010 at 3:48 pm

A few comments…
1. In the colorFade section you're declaring step twice.

2. Steps and speed as parameters don't really mean a whole lot. I changed those paramters to duration (in millisecons, not optional) and framesPerSecond (default of 24) so you can specify how smooth the animation is and how long the it should take:
function colorFade(id, element, start, end, duration, framesPerSecond) {
var steps,speed,startrgb,endrgb,er,eg,eb,step,rint,gint,bint;
var target = document.getElementByID(id);
framesPerSecond = framesPerSecond || 24;
steps = framesPerSecond * (duration / 1000);
speed = 1000 / framesPerSecond;
clearInterval(target.timer);

}

3. Theres a section in the colorFade function where you're setting color integers, then you check if the value is zero and set to 1 if it is. You could use the Math.max function instead:
rint = Math.max(Math.round(Math.abs(target.r-er) / steps), 1);

4. You should just pass target to the animateColor function instead of id, then you don't need to get the element in the animateColor function.

5. You've got a section in the animateColor function where your checking if the color is >= to the end color and adding or subtracting the increment (and parsing the values [only half the time] when they are already numbers). This could be written as:
var r = target.r;
var g = target.g;
var b = target.b;
r += (rint * (r >= er ? -1 : 1));
g += (gint * (g >= eg ? -1 : 1));
b += (bint * (b >= eb ? -1 : 1));

6. You've got 2 sections in the animateColor function where you're setting the style based of the element. First, you're declaring the color variable before the conditional, so you should remove both sections and move it to after the conditional. Second, change the whole conditional to just set the style of the element that is passed in:
function animateColor(…) {

var color;
if (target.step <= steps) {

color = 'rgb(' + r + ',' + g + ',' + b + ')';

} else {

color = 'rgb(' + er + ',' + eg + ',' + eb + ')';
}
target.style[element] = color;
}

Ryan R on January 11, 2010 at 5:01 pm

Thanks heaps for he script, its really great to see a nice clean transition.

Bateria blackbarry on August 09, 2010 at 2:40 pm

Loop fade:

Change

function animate(id……

to

function animateColor(id,element,steps,er,eg,eb,rint,gint,bint,speed,start,end,steps) {

Add at the end of that same procedure:

if (target.step == steps) {

colorFade(id,element,end,start,steps,speed)

}

David on August 16, 2010 at 8:57 pm

Very nice colour blend, thanks for the resource. LT

Lisa on August 26, 2010 at 8:00 am
Comments are closed at this time.