user818700
user818700

Reputation:

Use variables in JQuery .css() function

I'm trying to set an image's left and right values randomly using JQuery by doing the following:

var sides = ["left", "right"]
var currentSide = sides[Math.floor(Math.random() * sides.length)];
$("#"+currentImage).css({currentSide : "80px"});

So i have an array that contains either 'left' or 'right' which gets randomly selected and the CSS of the element gets set to either right: "80px"; or left: 80px;

But, its not working. When I go and set it statically e.g. $("#"+currentImage).css({"left" : "80px"}); then it works fine, so it's just passing variables to the .css() function that's making this break.

Any ideas?

Upvotes: 0

Views: 56

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388436

You are trying to create an object with a dynamic key, in that case you need to use bracket notation. In your case you are creating an object with key currentSide not left/right.

You can use

$("#"+currentImage).css(currentSide, "80px");

Upvotes: 3

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

I'll answer this a bit more generally so you don't run into this type of problem in the future, with other applications that may not have an alternate syntax like $().css() does. Using this method you can also assign multiple styles using a single .css() call.

var sides = ["left", "right"]
var currentSide = sides[Math.floor(Math.random() * sides.length)];
var styles = {};
styles[currentSide] = "80px";
$("#"+currentImage).css(styles);

Upvotes: 1

Related Questions