JavaScript Color Fading Script

Design, Javascript 94 responses so far

javascript color fading script

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.

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Michael (see all)

  • Pingback: Webmaster Libre | Transiciones de color con Javascript

  • http://dabrook.org Zac

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

  • http://www.leigeber.com Michael

    @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)”>

  • http://letstalkdev.com Web Development Blog

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

  • Pingback: » JavaScript Color Fading Script Webcreatives

  • Pingback: JavaScript Color Fading Script

  • Mario

    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

  • http://www.leigeber.com Michael

    @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.

  • http://sitesquared.com Shanna

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

  • Pingback: Intenta » Blog Archive » Links 05-05-2008

  • http://zero1infinity.tumblr.com Zero1infintiy

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

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

  • Nate

    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.

  • http://www.leigeber.com Michael

    @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.

  • Pingback: Max Design - standards based web design, development and training » Some links for light reading (6/5/08)

  • http://arlingtonreads.org(comingsoon) RP

    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

  • hamochi

    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

  • http://www.leigeber.com Michael

    @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 };

  • Pingback: Exceptional Ajax/javascript Techniques (Recently Created)

  • Pingback: 30 recently created exceptional ajax javascript techniques

  • http://www.gomscs.com Curt

    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. :)

  • http://www.leigeber.com Michael

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

  • http://www.crimsonmonkeyweb.com Ryan

    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

  • Pingback: Leigeber: Web Development Blog | CNET.ro

  • Marcus

    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

    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

  • Pingback: StarryNight » Blog Archive » 最新ajax特效30则

  • http://www.tglservices.co.uk TGLS

    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.

  • http://www.leigeber.com Michael

    @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.

  • elvis

    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.

  • http://www.leigeber.com Michael

    @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.

  • http://mcdowellcrook.com mcd

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

  • http://www.leigeber.com Michael

    @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.

  • http://www.kurtluther.com Kurt

    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?

  • http://www.leigeber.com Michael

    @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.

  • http://www.yachtpartnership.org/yacht_preview.html Parker

    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.

  • Palle Nielsen

    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

  • http://redseacheck.com roger  

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

  • http://redseasound.com/blog roger  

    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

  • JG

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

  • Michael

    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)

  • mimi

    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.

  • http://www.leigeber.com Michael

    @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.

  • LP

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

  • Pingback: Codigos Web » Blog Archive » Transiciones de color con Javascript

  • http://trustreliable.com Jesse

    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

  • http://www.uaarg.de patte

    @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

  • http://www.jagonetwork.co.uk Daniel Harrison

    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

  • Steve

    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.

  • Chad

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

  • Chad

    @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

  • http://macaoidh.name conor

    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

  • Pingback: Ajax/javascript Techniques | Design it

  • http://notyetintheair Michael

    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

  • Pingback: ajax特效 | forcto.com

  • http://www.blackberrybrasil.com.br tresloukadu

    awesome man ….. its working very good…

  • Jan

    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 !

  • http://www.vtwebproperties.com Ed Rooney

    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.

  • http://www.kdonkey.nl Kdonkey

    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

  • Ant

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

  • Ant

    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">

  • http://www.multiwebdigital.com.br Bruno Camargos

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

  • Stephanie

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

  • Pingback: 30个精挑细致的Ajax和Javascript 技巧 | 帕兰映像

  • Pingback: gamma agency – javascript color fading

  • skux

    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.

  • mrpink

    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);

  • Monty

    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!

  • sketch

    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?

  • david

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

  • Patrick

    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

    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.

  • Viv

    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>

  • Pingback: Sharebrain JavaScript Color Fading Script »

  • Ryan R

    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;
    }

  • Pingback: Exceptional Ajax/javascript Techniques (Recently Created) | amitkosti.name

  • http://www.daveodonoghue.com David

    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)

    }

  • Eoin

    This is something I have been looking for a while now. I was looking to do something for borders around images and this is perfect for it! Thanks a million.

  • George

    Good morning to everyone. First of all thanks for this!Great site and great resources found there. I'm facing a strange issue with this function and I would like some advice by a more experienced developer. I'm applying this function to a <tr>. The contents of the table are dynamically generated with json. The first time I apply the function everything works perfect. But then the animation does no longer works and I'm trying to find out why! Any suggestions?

  • http://www.facebook.com/ryein.goddard Ryein Cardale Goddard

    I was messing around with some stuff for an ART class and I used your script. Thought I would show anyone interested.

    http://www.goddardlabs.com/art/symmetry1.html

    You can kind of gauge performance with this as well. At times it has up to 1,764 commands being ran at once.

  • Anonymous

    Very cool stuff, thanks for sharing.

  • Anonymous

    url?

  • http://openid.axel-k.com/ axel

    Grate script!! Thank you for sharing it.
    ¿Is there a way to apply transparency to the transition?

    I'm using it for the background color.

  • http://www.hi-techwebmaster.com Web Designing Jodhpur

    Great Script. Thanks buddy!!

  • http://twitter.com/jonnydarkmusic Jonny Dark

    Excellent script! It even works in conjunction with CSS fallback when using it to have links change colour on mouseover. Nicely done!

  • Zeclubbeur

    Hello !
    I've got the same issue.
    I've found a "patch" to correct this : 

    replace
    if (!target.r) {
    target.r = r;target.g = g;target.b = b;

    }
    by
    target.r = r;target.g = g;target.b = b;

  • Bahlawi89

    Thanks Man for your great job.

    http://www.tec-world.info 

    I will paraphrasing and post in my website and backlink to you

  • adumpaul

    Nice javascript code.Thank you for sharing.

  • http://www.cyberdesignz.com/services/web-designers flash web designer

    Nice post!
    Thanks for sharing your experience.

  • Bruni1974

    Is there a way to use this script for the background of the page?
    v1: the background color changes smooth only while moving the mouse
    v2: the background color changes smooth automatically with preset colors

    Thanks a lot!

  • JF Lanouette

    Its was buggy for me i fixed it …
    // main function to process the fade request //

    functionfunction

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

    var startrgb,endrgb,er,eg,eb,rint,gint,bint;

    var target = document.getElementById(id);

    steps = steps || 20;
    speed = speed || 20;
    clearInterval(target.timer);
    endrgb = colorConv(end);
    er = endrgb[0];
    eg = endrgb[1];
    eb = endrgb[2];

    steps = steps || 20;

    speed = speed || 20;

    clearInterval(target.timer);

    endrgb = colorConv(end);

    er = endrgb[0];

    eg = endrgb[1];

    eb = endrgb[2];

    if (element == 'background') {

    target.style.backgroundColor =
    target.style.backgroundColor =
    "#" + start;

    }
    }
    else if (element == 'border') {

    target.style.borderColor =
    target.style.borderColor =
    "#" + start;

    }
    }
    else {

    target.style.color =
    target.style.color =
    "#" + start;

    }

    startrgb = colorConv(start);

    }

    startrgb = colorConv(start);

    var r = startrgb[0];

    var g = startrgb[1];

    var b = startrgb[2];

    target.r = r;
    target.g = g;
    target.b = b;

     
    rint = Math.round(Math.abs(target.r-er)/steps);
    gint = Math.round(Math.abs(target.g-eg)/steps);
    bint = Math.round(Math.abs(target.b-eb)/steps);

    target.r = r;

    target.g = g;

    target.b = b;

     

    rint = Math.round(Math.abs(target.r-er)/steps);

    gint = Math.round(Math.abs(target.g-eg)/steps);

    bint = Math.round(Math.abs(target.b-eb)/steps);

    if(rint == 0) {rint = 1; }

    if(gint == 0) {gint = 1; }

    if(bint == 0) {bint = 1; }

    target.step = 1;
    target.timer = setInterval(
    target.step = 1;

    target.timer = setInterval(
    function () { animateColor(id, element, steps, er, eg, eb, rint, gint, bint); }, speed);

    }

    // incrementally close the gap between the two colors //
    function
    }

    // incrementally close the gap between the two colors //
    function
    // incrementally close the gap between the two colors //

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

     

     

    var target = document.getElementById(id);

    var color;

    if(target.step <= steps) {

    var r = target.r;

    var g = target.g;

    var b = target.b;

    if(r >= er) {

    r = r – rint;
    }
    r = r – rint;

    }
    else {

    r = parseInt(r) + parseInt(rint);
    }

    r = parseInt(r) + parseInt(rint);

    }

    if(g >= eg) {

    g = g – gint;
    }
    g = g – gint;

    }
    else {

    g = parseInt(g) + parseInt(gint);
    }

    g = parseInt(g) + parseInt(gint);

    }

    if(b >= eb) {

    b = b – bint;
    }
    b = b – bint;

    }
    else {

    b = parseInt(b) + parseInt(bint);
    }

    color =
    b = parseInt(b) + parseInt(bint);

    }

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

    if(element == 'background') {

    target.style.backgroundColor = color;
    }
    target.style.backgroundColor = color;

    }
    else if(element == 'border') {

    target.style.borderColor = color;
    }
    target.style.borderColor = color;

    }
    else {

    target.style.color = color;
    }
    target.r = r;
    target.g = g;
    target.b = b;
    target.step = target.step + 1;
    }
    target.style.color = color;

    }

    target.r = r;

    target.g = g;

    target.b = b;

    target.step = target.step + 1;

    }
    else {

    clearInterval(target.timer);
    color =
    clearInterval(target.timer);

    color =
    'rgb(' + er + ',' + eg + ',' + eb + ')';

    if(element == 'background') {

    target.style.backgroundColor = color;
    }
    target.style.backgroundColor = color;

    }
    else if(element == 'border') {

    target.style.borderColor = color;
    }
    target.style.borderColor = color;

    }
    else {

    target.style.color = color;
    }
    }

    }

    // convert the color to rgb from hex //
    function
    target.style.color = color;

    }

    }

    }

    // convert the color to rgb from hex //
    function
    // convert the color to rgb from hex //

    function
    function
    colorConv(color) {

    var rgb = [parseInt(color.substring(0,2),16),

    parseInt(color.substring(2,4),16),
    parseInt(color.substring(4,6),16)];

    parseInt(color.substring(2,4),16),

    parseInt(color.substring(4,6),16)];

    return rgb;

    }
    }

  • http://www.facebook.com/talktobazz Michael Bazzinotti

    works great :) , but I did modify it to directly take elements instead of id :)

  • KFC

    HEY MAFAKAS!!!! c:

  • KFC

    I am a single independent woman who dont need no man!

  • Jarred-Awesome

    Awesome script.

    I used this for a app I am working on. I altered it because I wanted it to work with jquery.
    Since Jquery can get most of the information you require in your function call, I altered it to automatically put in the relevant information.

    For example, You don't need to tell it what element to switch, I also up dated the function colorconvert so it can accept both hex and rgb.

    There where a few examples of long winded code, so I fixed those too!

    Let me know what you think.
    $.fn.bgFade = function(end, steps, speed){
    var startrgb,endrgb,er,eg,eb,step,rint,gint,bint,step;
    var target = $(this[0]);
    var start = target.css('backgroundColor');

    var animateColor = function(steps,er,eg,eb,rint,gint,bint){
    var color;
    if(target.step <= steps){
    target.r = (target.r < er) ? (parseInt(target.r) + parseInt(rint)) : parseInt((target.r – rint));
    target.g = (target.g < eg) ? (parseInt(target.g) + parseInt(gint)) : parseInt((target.g – gint));
    target.b = (target.b < eb) ? (parseInt(target.b) + parseInt(bint)) : parseInt((target.b – bint));
    color = 'rgb(' + target.r + ',' + target.g + ',' + target.b + ')';
    $(target).css('backgroundColor', color);
    target.step = target.step + 1;
    }else{
    clearInterval(target.timer);
    color = 'rgb(' + er + ',' + eg + ',' + eb + ')';
    $(target).css('backgroundColor', color);
    }
    }

    var colorConv = function(h){
    var hexdec = function(hex_string){return parseInt((hex_string + '').replace(/[^a-f0-9]/gi, ''), 16);}
    var hexLength = h.length;
    if(/^rgb((d+),s*(d+),s*(d+))$/.test(h)){
    var t = h.match(/^rgb((d+),s*(d+),s*(d+))$/);
    return [t[1], t[2], t[3]];
    }else if(/^#([A-Fa-f0-9]{6})$/.test(h)){
    h = (h.charAt(0)=="#") ? h.substring(1,7) : h;
    return [hexdec(h.substring(0,2),16), hexdec(h.substring(2,4),16), hexdec(h.substring(4,6),16)];
    }else if(/^#([A-Fa-f0-9]{3})$/.test(h)){
    h = (h.charAt(0)=="#") ? h.substring(1,4) : h;
    return [hexdec(h.substring(0,1)+""+h.substring(0,1)), hexdec(h.substring(1,2)+""+h.substring(1,2)), hexdec(h.substring(2,3)+""+h.substring(2,3))];
    }
    return '[0,0,0]';
    }

    steps = steps || 20;
    speed = speed || 20;
    clearInterval(target.timer);
    endrgb = colorConv(end);
    er = endrgb[0];
    eg = endrgb[1];
    eb = endrgb[2];
    if(!target.r){
    startrgb = colorConv(start);
    target.r = startrgb[0];
    target.g = startrgb[1];
    target.b = startrgb[2];
    }
    rint = Math.round(Math.abs(target.r-er)/steps);
    gint = Math.round(Math.abs(target.g-eg)/steps);
    bint = Math.round(Math.abs(target.b-eb)/steps);
    if(rint == 0) { rint = 1 }
    if(gint == 0) { gint = 1 }
    if(bint == 0) { bint = 1 }
    target.step = 1;
    target.timer = setInterval( function() { animateColor(steps,er,eg,eb,rint,gint,bint) }, speed);
    }

    p.s. I only needed it to change bg color, so I altered it to do it that way

x
Loading...