2

It is possible to use a variable as a value:

$("#anything").css({
    "top": value
});

But if I try the opposite:

toporbottom = "top";
$("anything").css({
    toporbottom: "50px"
});

it doesnt work. Is there a elegant solution?

4 Answers 4

1

In your case, you don't need an object because you're only setting one property. Use:

$(...).css(toporbottom, "50px");

If you do want an object, you'll have to make an empty one first, then set the property using the [...] notation, and pass obj. But this is definitely overkill here:

var obj = {};
obj[toporbottom] = "50px"; // `obj["top"]` is the same as `obj.top`
$(...).css(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

This works best because I can also use it with .animate()! Thanks!
1

In that case, you can call css using the name and value as individual arguments:

toporbottom = "top"; 
$("anything").css(toporbottom, "50px");

Comments

1

Sure it is. Use the alternate .css syntax.

$(document).ready(function(){
    var topOrBottom = "top";

    $("#changeme").css(topOrBottom, 200);
});

Comments

1

Object literal does not support variable as key. Key should be always constant. However you can use the [] to set a property.

toporbottom = "top";
var obj = {};
obj[toporbottom] = "50px"; // Line of interest
$("anything").css(obj);

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.