Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
ES5 quote that says it should not work
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
This means that:
{ theTop : 10 }
is the exact same as{ 'theTop' : 10 }
The
PropertyName
theTop
is anIdentifierName
, so it gets converted to the'theTop'
string value, which is the string value of'theTop'
.It is not possible to write object initializers (literals) with variable keys.
The only three options are
IdentifierName
(expands to string literal),StringLiteral
, andNumericLiteral
(also expands to a string).Rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
I have used the following to add a property with a "dynamic" name to an object:
key
is the name of the new property.The object of properties passed to
animate
will be{left: 20, width: 100, top: 10}
This is just using the required
[]
notation as recommended by the other answers, but with fewer lines of code!This way also you can achieve desired output
{ thetop : 10 }
is a valid object literal. The code will create an object with a property namedthetop
that has a value of 10. Both the following are the same:In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
You can use this new syntax in the latest versions of each mainstream browser.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
Where
key
can be any sort of expression (e.g. a variable) returning a value.So here your code would look like:
Where
thetop
will be replaced by the variable value.You could do the following for ES5:
Or extract to a function: