Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dynamic variable as object literal, jQuery animate function

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,
like image 466
Titan Avatar asked Dec 02 '22 21:12

Titan


1 Answers

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;
like image 85
Halcyon Avatar answered Dec 10 '22 13:12

Halcyon