0

Possible Duplicate:
Using a dynamic variable as object literal, jQuery animate function

I'm attempting to pass a function argument as a setting for a jquery animation except I cannot get it working.

The Function

function gridClick(a, b){
    $(c).animate({
        a : 0,
        b : 0
    }, 10000)
};

calling the function

gridClick('top', 'left', this);

console log shows that a and b are being put out as top and left but they are not actually affecting the animation as top and left. Is this a syntax error or is there more going on?

Community
  • 1
  • 1
  • 2
    possible duplicate of [Using a dynamic variable as object literal, jQuery animate function](http://stackoverflow.com/questions/13236473/using-a-dynamic-variable-as-object-literal-jquery-animate-function) and [Setting object keys from variables](http://stackoverflow.com/questions/12864544/setting-object-keys-from-variables). – Felix Kling Dec 17 '12 at 18:56
  • Is `c` meant to be a third argument to the function? – freejosh Dec 17 '12 at 18:56
  • yes but c is unrelated to this issue. – swgamerx150 Dec 17 '12 at 19:03

2 Answers2

0

I don't think you can use a variable name as an object's property name using object literal. Here is one possible workaround:

function gridClick(a, b) {
    var params = {};
    params[a] = 0;
    params[b] = 0;
    $(c).animate(params, 10000);
};
Salman A
  • 262,204
  • 82
  • 430
  • 521
0

If you want to use variables for property names, you will need to use bracket notation and assignments. The literal syntax does not support it.

Instead, use:

function gridClick(a, b, c) {
    var opts = {};
    opts[a] = 0;
    opts[b] = 0;
    $(c).animate(opts, 10000)
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
Bergi
  • 630,263
  • 148
  • 957
  • 1,375