views:

38

answers:

1

Hi

I'm using jQuery's animate function like this:

var css1 = {
      display: "block",
      marginTop: 20
    };

var direction = "marginTop";

$(element).animate(css1, 150, 'swing'); 

Notice the marginTop property above. Well I want to replace that with the direction variable, but it doesn't work for some reason. Does anyone know why?

Later edit: Basically I want to replace:

var css1 = {
      display: "block",
      marginTop: 20
    };

with

var css1 = {
      display: "block",
      direction: 20
    };

The problem is that jQuery doesn't seem to recognize "direction" as the "marginTop" property

+2  A: 

You can do a dynamic property like you want using bracket notation, like this:

var direction = "marginTop";
var css1 = { display: "block" };
css1[direction] = 20;

$(element).animate(css1, 150, 'swing');

Doing css1.marginTop can also be accessed via css1["marginTop"], and you can use a variable for the second (bracket notation) version.

Nick Craver
thank you, that was it :D
Alex