2

Is it possible to 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 I can get it to work is by repeatedly declaring the lines separately, such as:

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

Does anyone have any other ideas? The reason I'm bothering with this is because I would like to be able to flip my module by 90 degrees (aka, have it go left to right or top to bottom), and to do that I'd have to have a universal variable for direction.

2 Answers 2

10

{ "top": var1, "height": var2 } creates a JavaScript Object that has two user-defined properties. Unfortunately, JavaScript does not allow you to use variables as property names when defining an Object in this way.

You should be able to do it like this:

var o = {};
o[dir] = var1;
o[length] = var2;
$("div").css(o);
Sign up to request clarification or add additional context in comments.

1 Comment

This is a really interesting solution. I'm going to have to give it more thought, but it definitely answers the question. Thanks!
1

Try this...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.