0

I have the following function:

$("#myId").css({left: leftVal+"px", top:topVal+"px"});

this works.

I am looking for a way to add left: leftVal+"px", top:topVal+"px" as a variable and make my function:

$("#myId").css({myCSSstuff});

I've tryed

var myCSSstuff= "left: "+leftVal+"px, top:"+topVal+"px"

but it does not work. Is there a way to do this? Thanx.

1 Answer 1

4

You can do it like this:

var myCSSstuff = { left: leftVal, top: topVal };
$("#myId").css(myCSSstuff);

The {} notation is for objects or associative arrays.

There are two ways you can add more properties:

myCSSstuff.color = 'red';
myCSSstuff['color'] = 'red';

The second approach allows you to use strings for the property name, i.e.

var prop = 'color';
myCSSstuff[prop] = 'red';
Sign up to request clarification or add additional context in comments.

2 Comments

and you can omit the 'px' part. (jquery handles that automatically)
thanx, this works!. What if I need to add another variable in the array at some point. Something like myCSSstuff = myCSSstuff + {color: something}. How can I do that? Thanx again

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.