JQuery Variables as Key in Key: CSS Attribute Pairs

Can I take something like:

$("div").css({
    "top": var1,
    "height": var2,
     etc.
});

      

And turn it into:

var dir = "top";
var length = "height";

$("div").css({
    dir: var1,
    length: var2,
     etc.
});

      

So far, the only way to make it work is to declare strings multiple times separately, like this:

$("div").css(dir, var1);
$("div").css(length, var2);
$("div").css(etc.);

      

Does anyone have any other ideas? The reason I am worried about this is because I would like to flip my module 90 degrees (aka go left to right or top to bottom), and for that I would have to have a universal variable for direction.

Thanks in advance!

+2


source to share


2 answers


{ "top": var1, "height": var2 }

creates a JavaScript object that has two custom properties. Unfortunately JavaScript does not allow variables to be used as property names when defining an object this way.

You should do it like this:



var o = {};
o[dir] = var1;
o[length] = var2;
$("div").css(o);

      

+9


source


Try it...



var myCss = {};
myCss[dir] = var1;
$("div").css(myCss);

      

+1


source







All Articles