0

I've been trying to figure this out for a good hour and I know it'll be super basic for someone out there. I'm trying to set a background with jQuery based on a variable called $the_path.

Right now the background is getting set to "$the_path" instead of the actual value of $the_path. How can I can the statement to evaluate properly?

$('body').css({'background' : 'url($the_path)','backgroundPosition' : 'center 50px'}); 

Many Thanks!

11
  • $the_path mean ? is it the js veriable ? Commented Oct 26, 2011 at 4:53
  • $the_path = 'images/image1.jpg'; Commented Oct 26, 2011 at 4:56
  • It will always equal a relative path to an image. Commented Oct 26, 2011 at 4:56
  • $the_path is php function i guess ? Commented Oct 26, 2011 at 4:58
  • if yes then you have to use this code of piece. $('body').css({'background' : "url('+ <?php echo $the_path; ?> +')",'backgroundPosition' : 'center 50px'}); Commented Oct 26, 2011 at 4:59

3 Answers 3

1

If you keep it in quotes, it'll be treated literally. To force it to be evaluated as a variable, break out of the quotes and join it using + instead.

$('body').css({'background' : "url('" + the_path + "')",'backgroundPosition' : 'center 50px'}); 

Edit: That's presuming $the_path is a Javascript variable. If it's a PHP variable, then you want this instead:

$('body').css({'background' : "url('<?=$the_path?>')",'backgroundPosition' : 'center 50px'}); 
Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm that still doesn't seem to be doing it. It's a javascript variable. Are we maybe confusing jQuery too much with all the stuff inside .css()?
Is $the_path from PHP ? It's a bit confusing what you mean as JS string variables don't typically begin with $. Have you tried both of my examples, exactly as written ? Also, try changing 'background' in the CSS to 'background-image' instead.
I use $ in variables for cached jQuery objects but I wouldn't use it for any other variables.
Your first example ended up working after I got rid of the $. I've been writing PHP all night and forgot to stop using the $. Thanks again!
0

'background' : 'url('+$the_path+')' is what you need.

Comments

0
var path = 'url(' + <? $the_path ?> + ')'; $('body').css({'background' : path, 'backgroundPosition' : 'center 50px'}); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.