views:

44

answers:

2

I'm trying to apply unknown styles to unknown selectors and it would seem that shorthand css cannot be applied using jQuery's .css() method. Is this correct? Is there a work-around?

Note that I am building the object dynamically to be passed in to the .css() and do not want to use .css('background','#000') syntax.

$('#example').css({background:'#000000 url("images/bg.gif") repeat-x scroll 0 0 transparent'});

The code above doesn't work. However, the code below does.

$('#example').css({background:'#000'});

And so does this.

$('#example').css({background:'url("images/bg.gif")'});

But when used together they naturally overwrite each other. Any suggestions?

+2  A: 

Your better option would be to have a set of pre-defined CSS classes in your CSS file and then apply those target styles on the fly as necessary.

This has the added benefit of keeping your jQuery code down to a readable and manageable level.

So instead of writing:

$('#example').css({background:'url("images/bg.gif")'});

You can opt for the simpler:

$('#example').addClass('myClass1');
Phil.Wheeler
I'm trying to apply unknown styles to unknown selectors so this isn't an option but would be the obvious choice.
sparksm
+4  A: 
background: #000000 url("images/bg.gif") repeat-x scroll 0 0 transparent;

… is invalid CSS. You've specified the background-color twice (#000000 and transparent). It should work if you use valid CSS.

That said, using classes and external stylesheets is usually a better bet.

David Dorward
Oo! Good spotting!
Phil.Wheeler
omg, I feel stupid...
sparksm