0

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 ?

0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

5 Comments

because OP is passing the CSS property as object.. :)
@EhsanSajjad Well, you can't, today, build a literal object with a dynamic property name. See developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
@dystroy You can, if you use a browser that supports ES6 computed property names, like Firefox 34.
I had already managed with you're fisrt solution, but it becomes à problem when you have more than one property to update.
That said, I wasn't aware of that object building thing. That's what i was after. This is very helpfull, thanks :)
2

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.

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.