Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS / jQuery : Variable .css() propertyName

How can I store property name as a variable?

Example code:

var propertyName = 'margin-top';
$('elem').css({ propertyName : '10px' });
like image 995
vlad Avatar asked May 29 '26 08:05

vlad


1 Answers

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.

like image 93
Daniel Weiner Avatar answered May 31 '26 23:05

Daniel Weiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!