2

Anyone know why this isn't working?

$('#screen').css({
  'background-image': [bg_num == 1 ? 'josh' : 'jessi'] + '_background.jpg',
  'background-color': 'red'
 });

The background color is getting set, but the image is not.

I've not really had much practice using square brackets in Javascript to get this kind of thing done. Anyone have tips if I'm doing something way wrong? Or no of a nice explanation of their use?

EDIT: And just to be clear, the check itself is actually happening, because if I do the same thing in a console.log() is outputs "josh_background.jpg" just fine. It's just not taking in this css setting function.

Ian Storm Taylor
  • 8,520
  • 12
  • 55
  • 72
  • 1
    I'm confused, what is it you think brackets mean in Javascript (hint: they are not equivalent to parentheses)? – Kirk Woll Jan 12 '11 at 19:14

1 Answers1

6

EDIT:

What you were doing was creating an Array literal with the value 'josh' or 'jessi', then concatenating '_background.jpg' onto it, so it technically would work.

The issue is that you're missing the 'url()' part of the background-image value.

'background-image': 'url(' + (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg)',

...but you should still use the () for grouping instead of constructing an Array.


Original answer:

Use parentheses for grouping instead of square brackets:

'background-image': (bg_num == 1 ? 'josh' : 'jessi') + '_background.jpg',

The only use you'll have for square brackets in javascript will be for getting/setting a property on an object, or for creating an Array literal:

var arr = []; // An Array literal

arr[10] = 'someArrValue'; // set index 10


var obj = {};  // A plain object literal

obj['prop'] = 'someObjValue';  // set the "prop" property

var key = 'prop2';

obj[key] = 'someOtherObjValue'; // set the property referenced in the "key" variable

...oh, they have use in regular expression syntax of course...

user113716
  • 318,772
  • 63
  • 451
  • 440