2

Hey I'm wonder what's the difference between these 2 codes? The first works but the 2nd doesnt?

First >>
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({'margin-left':$masterWidth});
...
}

Second >>
$propToAnimate = 'margin-left';
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({$propToAnimate:$masterWidth});
...
}
hamahama
  • 393
  • 2
  • 5
  • 17

2 Answers2

6

This is a working solution...

$propToAnimate = {'margin-left': $masterWidth};
$($sequencingArray[i]).delay(i*100).animate($propToAnimate);

"You cannot use a variable as a property name inside an object literal." from here

Community
  • 1
  • 1
wdm
  • 7,121
  • 1
  • 27
  • 29
0

When you are using {'margin-left':$masterWidth} or {$propToAnimate:$masterWidth}you are creating an object. So we need to know what we are doing when we create an object using the Object Initializer ({k0:v0, k1:v1}) syntax.

Most importantly for your case var a = {prop:20} and var a = {'prop':20} will both do exactly the same thing -- create an object with one property called prop. It doesn't matter if you had already said var prop = 'different' elsewhere, prop is just treated as a literal name when used in {prop:20} and is not evaluated.

What you could do to make the second version of your code work, is make use of the a['prop'] syntax for objects. So something like:

var prop = 'margin-left';
var obj = {}; // Create a new object with no propeties
obj[prop] = masterWidth; // Add a new property to obj (using the value of the variable prop as the name of the new property)

Then you will have obj['margin-left'] == masterWidth. And you can use this object in the animate function... animate(obj);

I hope I haven't been too confusing!

mkkane
  • 63
  • 1
  • 4