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;
source share