Using a dynamic variable as an object literal, jQuery animation function

I originally 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 that will not work.

I tried

 direction.toString() 

and

 ''+direction+'' 

No joy from this either

 var anim = { direction: "+=100%" } targetWater.animate(anim, 
+4
source share
6 answers

Your approach does not work, because direction interpreted as a key, not a variable.

You can do it like this:

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

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


If you need a "direction" key with a square bracket, you must write:

 animation["direction"]; 

which is equivalent to:

 animation.direction; 
+8
source

Use parenthesis notation:

 var anim = {}; anim[direction] = "+=100%"; 
+2
source

You do not get the interpolated variable, you need to define it as follows:

 var options = {}; options[direction] = "+=100%"; targetWater.animate( options , /*...*/ 
+2
source

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

 var direction = (targetWater.hasClass('x'))? "width" : "height"; var animProp = {}; animProp[direction] = "+=100%"; targetWater.animate(animProp, /*..*/); 
+2
source

You can use the "Array-like" notation (parenthesis) to create a "correct" / dynamic property:

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

No, you cannot use variables inside keys. Or you create an object using notation brackets

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

or you are not using an object

 targetWater.animate(targetWater.hasClass('x') ? "width" : "height", "+=100%", โ€ฆ 
+2
source

Source: https://habr.com/ru/post/1444157/


All Articles