Reputation: 113
I want to set CSS properties by a variable: e.g. {background: red; }
My code has a mistake, it does not work: js fiddle
js
var Key = 'background';
var Value = 'yellow';
$('.test').css({
Key: Value
});
Upvotes: 1
Views: 601
Reputation: 5578
If you want to use the plain object css
overload, then you will need to do it like this:
$('.test').css({
'background': Value
});
Or
var properties ={};
var Key = 'background';
var Value = 'yellow';
properties[Key] = Value;
$('.test').css(properties);
The problem with {Key: Value}
is that it thinks the property name is Key
and not background
.
Upvotes: 1
Reputation: 74738
See there are two ways of applying css to an element with jQuery:
$(selector).css("propertyname","value");
$(selector).css({"propertyname":"value"}); // object with key : value pair
What is the issue in your code?
The issue is
{Key:Value}
object key which has to be a string ("") so that does not work in your case your best bet to go with first one:
$('.test').css(Key, Value);
to understand this go to this Fiddle
Upvotes: 2
Reputation: 25527
It should be like .css("propertyname","value")
. So your code will need to change like
$('.test').css(Key, Value);
See this for more reference
Upvotes: 3