How can I store property name as a variable?
Example code:
var propertyName = 'margin-top';
$('elem').css({ propertyName : '10px' });
How can I store property name as a variable?
Example code:
var propertyName = 'margin-top';
$('elem').css({ propertyName : '10px' });
You can store the argument for css() as a variable, and then add the property to it:
var propertyName = 'margin-top';
var cssArg = {};
cssArg[propertyName] = '10px';
$('elem').css(cssArg);
Edit:
In the future (ES6) you'll be able to do that in one line using computed properies:
$('elem').css({ [propertyName] : '10px'});
But for now, you have to stick with the long way.
For single CSS directive change, you could simply do this:
var propertyName = 'margin-top';
$('elem').css(propertyName, '10px');
If you still need to pass Object in order to manipulate multiple directives, you could try this:
var cssData = {};
var propertyName = 'margin-top';
cssData[propertyName] = '10px';
$('elem').css(cssData);
See Documentation