0

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?

1
  • why not $("#"+currentImage).css( currentSide , "80px" ); doc? Commented Feb 17, 2015 at 8:35

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments