2

I'm running into a rather odd problem that I just can't seem to solve. I'm trying to use a variable in the .css() but it doesn't work. However if I type in 'background-color' directly within the .css() call it does. What gives?

var css = that.data('css'); var targets = that.data('targets'); var value = that.val(); console.log(css + ' ' + targets + ' ' + value); console.log(css === 'background-color'); // returns true $(targets).css({ css: value }); // Doesn't work! $(targets).css({ 'background-color': value }); // Works ok! 

3 Answers 3

4

You cannot use a variable as a key in an object literal, create the object first then use bracket notation to add the property

 var obj = {}; obj[css] = value; $(targets).css(obj); 

or simply

 $(targets).css(css, value); 
Sign up to request clarification or add additional context in comments.

Comments

2

You can't use a variable as an identifier in an object literal. Using { css: value } creates an object with a property named css, it's not using the variable css.

Create an object and set the property:

var o = {}; o[css] = value; $(target).css(o); 

Comments

0

This works too. Try removing the curly braces inside .css() and use a comma instead of colon.

 var css = 'background-color'; var targets = '#hellowhat'; var value = '#000'; $(""+ targets +"").css( css, value); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.