4

Originally I had

targetWater.animate({
    "width": "+=100%"

Now I want to dynamically use "width" or "height"

var direction = (targetWater.hasClass('x'))? "width" : "height";
targetWater.animate({
    direction: "+=100%"

But this doesn't work.

I've tried

direction.toString()

and

''+direction+''

No joy with this either

var anim = { direction: "+=100%" }
targetWater.animate(anim,
Titan
  • 5,567
  • 9
  • 55
  • 90

6 Answers6

8

Your approach doesn't work since direction is interpreted as a key, not a variable.

You can do it like so:

var animation = {};
var direction = targetWater.hasClass('x') ? "width" : "height"
animation[direction] = "+=100%";
targetWater.animate(animation);

The square brackets make it so you can have the key dynamically.


If you would want the key "direction" with the square bracket notation you would write:

animation["direction"];

which is equivalent to:

animation.direction;
Halcyon
  • 57,230
  • 10
  • 89
  • 128
2

Use bracket notation:

var anim = {};
anim[direction] = "+=100%";
moonwave99
  • 21,957
  • 3
  • 43
  • 64
2

You variable does not get interpolated, you need to define it the following way:

var options = {};
options[direction] = "+=100%";

targetWater.animate( options , /*...*/
Christoph
  • 50,121
  • 21
  • 99
  • 128
2

I would suggest you to create it as a property and pass it to the .animate function. See below,

var direction = (targetWater.hasClass('x'))? "width" : "height";

var animProp = {};
animProp[direction] = "+=100%";

targetWater.animate(animProp, /*..*/);
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

You could use "Array-like" (bracket) notation to create the "right"/dynamic property:

var animation = {};
animation[targetWater.hasClass('x'))? "width" : "height"] = "+=100%";

targetWater.animate(animation);
m90
  • 11,434
  • 13
  • 62
  • 112
2

No, you can't use variables inside keys. Either you build the object with bracket notation

var anim = {};
anim[ targetWater.hasClass('x') ? "width" : "height" ] = "+=100%";
targetWater.animate(anim, …

or you don't use an object

targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", …
Bergi
  • 630,263
  • 148
  • 957
  • 1,375