-2

I am attempting use a variable to fill in the property value of this CSS jQuery code. In the example below I am using an array to try to fill it in but it is giving me an error. I've attempted this without using it as an array where "tops" equaled "bottom" but still nothing.

var tops = [ '"top"', '"bottom"' ];
$(div).css({ tops[1] : 5 });
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user1636946
  • 137
  • 1
  • 3
  • 14

1 Answers1

1

You cannot use an expression as the literal key of an object. You need to use the singular setter of jQuery's css() method:

var tops = [ 'top', 'bottom' ]; // note only a single set of quotes around the values
$(div).css(tops[1], 5);

This is also assuming the div variable holds a DOMElement. If you want to select all div elements in the DOM, use a string selector: $('div').

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Nice. That worked perfectly. This was my end results var tops = ['top', 'bottom']; $(this).css(tops[Math.floor(Math.random() * 2)], Math.floor(Math.random() * 3) + 1); – user1636946 Mar 23 '16 at 15:00
  • Glad to help. Note that you can make the first part less rigid by reading the `length` property of the array: `tops[Math.floor(Math.random() * tops.length)]` – Rory McCrossan Mar 23 '16 at 15:45