Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if element has a background specified?

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?

like image 767
Snuffleupagus Avatar asked Nov 07 '12 22:11

Snuffleupagus


2 Answers

temporary element approach

It's not ideal, but you could create a temporary element when your js initiates, insert it somewhere hidden in the document (because if you don't you get empty styles for webkit browsers) and then read the default background style set for that element. This would give you your baseline values. Then when you compare against your real element, if they differ you know that the background has been set. Obviously the downside to this method is it can not detect if you specifically set the background to the baseline state.

var baseline = $('<div />').hide().appendTo('body').css('background');

var isBackgroundSet = ( element.css('background') != baseline );

If you wanted to avoid possible global styles on elements, that would break the system i.e:

div { background: red; }

... you could use the following instead, but I doubt if it would work so well with older browsers:

var baseline = $('<fake />').hide().appendTo('body').css('background');

background

I spent some time with a similar issue - attempting to get the original width value from an element when set to a percentage. Which was much trickier than I had assumed, in the end I used a similar temporary element solution. I also expected, as Rene Koch does above, that the getComputedStyle method would work... really annoyingly it doesn't. Trying to detect the difference between the source CSS world and the runtime CSS world is a difficult thing.

like image 127
Pebbl Avatar answered Nov 13 '22 16:11

Pebbl


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/

like image 1
Shmiddty Avatar answered Nov 13 '22 16:11

Shmiddty