Search code examples
javascriptcssjquery-easing

JavaScript -Change CSS color for 5 seconds - How to add easing effect?


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.


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