Alex Rivera | Logout

Detect if element has a background specified?

Asked 2012-11-07T22:01:01.647
8

I'm trying to determine if an element has a background explicitly set. I figured I could just check to see if .css('background')* was set, however, it's inconsistent between browsers. For example, chrome shows an element without a background set as

background: rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box
background-color: rgba(0, 0, 0, 0)
background-image: none

whereas IE8 shows

background: undefined
background-color: transparent
background-image: none

(test case here)

*(shorthand properties of CSS aren't supported for getting rendered styles in jQuery)

Short of handling each separate case is there a better way to detect this?

Edit
Report

1 Answer

1

This should work:

function isBGDefined(ele){
    var img = $(ele).css('backgroundImage'),
        col = $(ele).css('backgroundColor');

    return img != 'none' || (col != 'rgba(0, 0, 0, 0)' && col != 'transparent');
};

DEMO

I didn't bother to test against the background property because in the end, it will change the computed styles of either backgroundImage and/or backgroundColor.

Here's the code run against your test case (with another added): http://jsfiddle.net/WG9MC/4/

answered 2012-11-07T22:19:40.103

Your Answer