Steve
Steve

Reputation: 4898

How to tell in jQuery if an element's background is transparent?

If 'element' has a transparent background

$('element').css('background-color') 

returns 'transparent' in some browsers and 'rgba(0, 0, 0, 0)' in others.

I would have expected jQuery to have cross-browser way of telling us if an element has a transparent background.

Am I missing something?

Thanks

Upvotes: 2

Views: 2416

Answers (2)

Jimmie Johansson
Jimmie Johansson

Reputation: 1962

rgba(0,0,0,0) is the same as transparent. The last digit is how filled the color should be, 0 = transparent.

function background_color(element) {
    if (element.css('background-color') === 'rgba(0, 0, 0, 0)'){
        return 'transparent';
    }
    return element.css('background-color');
}

background_color($('element')) // will do the trick 

Upvotes: 4

megawac
megawac

Reputation: 11353

I'm not sure if this is too useful for you but you can add a custom cssHook and do the processing in there. You can also probably define it so you can modify the return of .css(background-color) but I don't have enough experience with cssHooks to know how to not cause it to infinitely recurse :/

$.cssHooks["nBackgroundColor"] = {//proxy to .css("background-color") called with .css("n-background-color")
    get: function(elem) {
        var back = $(elem).css("background-color");
        return back === "rgba(0, 0, 0, 0)" ? "transparent" : back;
    }, 
    set: function(elem, val){ return $(elem).css('background-color', val); }
};

$($("div")[10]).css('n-background-color');//=> transparent

Upvotes: 1

Related Questions