Schpr
Schpr

Reputation: 35

How to use a var value in place of a css property in a jQuery ".css()" method

I've got this :

$('.something').css({ 'margin-left' : '100px'});

Sometimes it needs to be changed to this :

$('.something').css({ 'right' : '100px'});


So I've been trying to put this in a string var as follow :

var css_prprty = 'margin-left';
if(change_needed){
    css_prprty = 'right';
}

$('.something').css({ css_prprty : '100px'});


It fails.
And for some reason it seems logical that it does, but I can't think of a way to resolve this.

Anyone know what would be the proper way to use a variable value in this case ?

Upvotes: 0

Views: 65

Answers (2)

Oriol
Oriol

Reputation: 288680

Your code doesn't work because css_property is an IdentifierName, so the resulting property name is its StringValue. Therefore, the following codes are equivalent:

var obj = { css_prprty : '100px'};
var obj = { "css_prprty" : '100px'};

Before EcmaScript 6, there is no way to use variables as property names when creating an object literal. You must create the object first, and then set the properties, using bracket notation:

var obj = {};
obj[css_prprty] = '100px';

EcmaScript 6 introduces computed property names, which allow you to do

var obj = { [css_prprty] : '100px'};

However, browser support is currently negligible.

For further information about how object literals are evaluated, see Runtime Semantics: Evaluation.

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382464

You have a simple solution :

$('.something').css(css_prprty,'100px');

Now, let's talk about the more general problem of building an object with a dynamic property name. You can't do it in one go, as a literal, you must do it in two steps :

var obj = {};
obj[css_prprty] = '100px';
$('.something').css(obj);

(as Oriol points it, there will be a shortcut in ES6)

Upvotes: 3

Related Questions