Question

With the reference to this question:-

JavaScript -Change CSS color for 5 seconds

Working demo of the answer:-

http://jsfiddle.net/maniator/dG2ks/

I need to know how i can add an easing effect to it, so that slowly and slowly color get 100% opaque and similarly get 100% transperent.

Was it helpful?

Solution

Code

function makeRGBStr(obj) {
    if (obj.a == null) return "rgb(" + obj.r + "," + obj.g + "," + obj.b + ")";
    else return "rgba(" + obj.r + "," + obj.g + "," + obj.b + "," + obj.a + ")";
}


window["highlight"] = function(obj, color) {
    var highlightColor = color || {
        "r": 255,
        "g": 0,
        "b": 0
    };


    var orig = obj.style.backgroundColor;
    var curAlpha = 1;
    obj.style.backgroundColor = makeRGBStr(highlightColor);
    setTimeout(function() {
        curAlpha -= 0.1;
        var newColor = highlightColor;
        newColor.a = curAlpha;
        obj.style.backgroundColor = makeRGBStr(newColor);

        if (curAlpha <= 0) {
            obj.style.backgroundColor = orig;
        }
        else {

            setTimeout(arguments.callee, 100);
        }
    });
}

jsFiddle: http://jsfiddle.net/dG2ks/32/

Some examples

OTHER TIPS

You can add the jquery library, combined with jquery ui - if you don't use it already - and use the switchClass method.

All info here : http://jqueryui.com/demos/switchClass/

It will only take 5 lines to do what you want :

Place jquery en jquery ui in the head section of your page (2 lines of code). These are the remotely hosted files, you can copy/paste the code 'as is'.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>

And then, at the end of the body, place a script that contains these three lines of code :

    $(".yourbutton".click(function() {
            switchClass('.currentclass','.redclass',500) 
            // transition from .currentclass to .redclass in 500 milliseconds
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top