views:

495

answers:

3

Hi!

Why does this work:

<something>.stop().animate(
    { 'top' : 10 }, 10
);

but this doesn't:

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 variable.

Thank you!

+3  A: 

try var thetop = 'top';

Reigel
thanks for the reply, but according to my tests this doesn't work either...
Marcel
@Marcel: Can you at least fix your code example to remove this bug? The more bugs there are in your code, the harder it is to guess which one it is that you want us to help you fix.
Mark Byers
yes - i was just about to do it - sorry for the quick and dirty code!
Marcel
+1  A: 

In the second top isn't even defined. What error do you get?

Update: he updated his question based on this answer. :)

New answer, as already pointed out, that the names of objects can't be variables in object literals.

Mark Byers
+10  A: 

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

You cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10; 

// Pass the resulting object to the animate method
<something>.stop().animate(
    aniArgs, 10  
);  
Andy E
+1 what I was typing :-) Another reminder that JavaScript object literals are not like mappings in Python.
bobince
@bobince: wow, it feels good to actually beat you to an answer for a change. It's usually the other way around - you must have fast fingers :-)
Andy E
+ 1 I was on the way to add that...
Reigel
I understand! Thank you!Shoudln't this also work with eval?I mean it doesn't work in my example at the moment, but I thin it should... :-)
Marcel
@Marcel: `eval()` wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, but `eval()` really shouldn't be used for such things. There's an excellent article on correct and incorrect usage of `eval`: http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx
Andy E
ok, in that case I will go for your solution (and check if i missused eval before) - thank you!
Marcel