4

I'm trying to create vars for some styles that i want to and reuse, but can't seem to get it to work. What am I doing wrong?

var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";  

$('.className').css({bgColor, textColor});

4 Answers 4

3

Taking a look at the documents on jquery css if you wanted to apply these values in a single call you'd need to create valid json. Per the documents:

var validValues = 
{ 
  "background-color": "#ffe", 
  "border-left": "5px solid #ccc" 
};

or

var validValues = 
{
  backgroundColor: "#ffe", 
  borderLeft: "5px solid #ccc" 
} 

then

$(selector).css(validValues);

Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name

specifically the reason yours does not work is the following does not create valid json for jquery:

var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";  

var json = {bgColor, textColor};

json =

{
  bgColor: "'background' : 'rgb(102,204,0)'", 
  textColor: "'color' : 'rgb(40,40,40)'"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Little faster on the draw than I am, but I'm going to include this working fiddle as an example. It uses the OP's original CSS requirements.
1

Try:

var bgColor = "rgb(102, 204, 0)";
var textColor =  "rgb(40, 40, 40)";

$('.className').css({ "background" : bgColor, "color" : textColor });

If you wanted to use a variable structure like JSON:

var styleJson = 
{
    'background' : 'rgb(102, 204, 0)', 
    'color' : 'rgb(40, 40, 40)'
}

$('.className').css(styleJson)

Comments

0

css basically refers to the style attribute in jquery.

In order to use it via js variables, you can convert it as an array.

var bgColor = ['background','rgb(102,204,0)'];
var textColor = ['color' , 'rgb(40,40,40)'];  


$('.className').css(bgColor[0], bgColor[1]);
$('.className').css(textColor[0], textColor[1]);

Example : http://jsfiddle.net/49byztbx/

Comments

0

You may also try this

var styles = {'background-color':'rgb(102,204,0)', 'color':'rgb(40,40,40)'}
$('.className').css(styles);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.