user3260177
user3260177

Reputation: 113

jQuery - CSS property in variable does not work

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

Answers (4)

row1
row1

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

Jai
Jai

Reputation: 74738

See there are two ways of applying css to an element with jQuery:

First:

$(selector).css("propertyname","value");

Second:

$(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

Anoop Joshi P
Anoop Joshi P

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

Milind Anantwar
Milind Anantwar

Reputation: 82231

use:

$('.test').css(Key, Value);

Working Example

Upvotes: 3

Related Questions