Using RGBA Colors in MSIE

© 16 April, 2013, Martin Rinehart

MSIE 8 and below do not support RGBA colors. This routine returns a color spec given rgba arguments. It returns RGBA if the browser supports it, otherwise it drops the alpha value and returns RGB.

Note that CSS is easier for this one. Set background-color or whatever to the rgb value. Then set it to the rgba value. If the browser supports rgba, the second one overrides the first. If the browser doesn't support rgba, the second one is ignored. CSS also lets you use an entirely different color for browsers without rgba support, which you may want.

Add your namespace prefix to all occurences of 'rgb' in the following:

/** Use RGBA, if supported. */
rgba = function ( red, green, blue, alpha ) {

    if ( rgba.ok === undefined ) { rgba.ok = is_ok(); }

    if ( rgba.ok ) { return 'rgba(' +
            red + ',' + green + ',' + blue + ',' + alpha + ')'; }
    else { return 'rgb(' + red + ',' + green + ',' + blue + ')'; }

    function is_ok() {
        var test_div = document.createElement( 'div' );
        try {
            test_div.style.backgroundColor = 'rgba(0,0,0, 0.0)';
            return true;
        }
        catch (e) { return false; }
    }

} // end rgba();

Thanks to Lea Verou's blog post and Kangax's comment therein.

Feedback: MartinRinehart at gmail dot com

# # #