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'; ta
Solution 1:
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;
Solution 2:
Use bracket notation:
var anim = {};
anim[direction] = "+=100%";
Solution 3:
You variable does not get interpolated, you need to define it the following way:
var options = {};
options[direction] = "+=100%";
targetWater.animate( options , /*...*/
Solution 4:
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, /*..*/);
Solution 5:
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);
Post a Comment for "Using A Dynamic Variable As Object Literal, Jquery Animate Function"