Jonathan
Jonathan

Reputation: 641

jQuery CSS background-image declaration?

This is what I have:

$("#list .active").closest('.header').css({
'background-color' : '#1a2e51',
'background-image' : '-webkit-gradient(linear, left top, left bottom, from(#2c3c6f), to(#071f31))',
'background-image' : '-webkit-linear-gradient(top, #2c3c6f, #071f31)',
'background-image' : '-moz-linear-gradient(top, #2c3c6f, #071f31)',
'background-image' : '-o-linear-gradient(top, #2c3c6f, #071f31)',
'background-image' : 'linear-gradient(to bottom, #2c3c6f, #071f31)'
});

Online example: http://jsfiddle.net/qSfvK/

However, it won't show me a gradient because I didn't write it well in jQuery, so how to do it?

EDIT

I can make it work in CSS but not in jquery, see what I mean by looking at this link:
http://jsfiddle.net/qSfvK/10/

Upvotes: 0

Views: 538

Answers (1)

jsonnull
jsonnull

Reputation: 415

This not a problem with the html or your selector, but instead the way the css map function works. In this case, you are not sending the browser a stylesheet that it can parse and decide which background statement to use. Instead, jQuery is overwriting the background-image property each time, so the final background-image property for any browser is the last, 'linear-gradient(to bottom, #2c3c6f, #071f31)'. You can test, as I did, this by removing the gradient lines that are incompatible with your browser and re-running the fiddle.

The way to fix this would be to add conditional lines of JavaScript that assign the appropriate background-image property according to which browser is being used.

So...

IF Safari 4+, Chrome 1-9 ...

$("#list .active").closest('.header').css({
    'background-color' : '#1a2e51',
    'background-image' : '-webkit-gradient(linear, left top, left bottom, from(#2c3c6f), to(#071f31))'
});​

ELSE IF Safari 5.1+, Mobile Safari, Chrome 10+ ...

$("#list .active").closest('.header').css({
    'background-color' : '#1a2e51',
    'background-image' : '-webkit-linear-gradient(top, #2c3c6f, #071f31)'
});​

ELSE IF Firefox 3.6+ ...

$("#list .active").closest('.header').css({
    'background-color' : '#1a2e51',
    'background-image' : '-moz-linear-gradient(top, #2c3c6f, #071f31)'
});​

ELSE IF Opera 11.10+ ...

$("#list .active").closest('.header').css({
    'background-color' : '#1a2e51',
    'background-image' : '-o-linear-gradient(top, #2c3c6f, #071f31)'
});​

And so on.

Upvotes: 1

Related Questions