tags:

views:

1236

answers:

3

I have this line of jQuery:

$("#colorimage").css('background','url(images/bw.jpg)');

First question: the way that this is working, when the background image is set with CSS via jQuery, from where is it looking for the images folder?

Second question: is there a way I can insert a Javascript variable into the second argument? I have a base url stored in a js variable but doing something like this:

$("#colorimage").css('background','url(' +  baseurl + 'images/bw.jpg)');

doesn't work.

EDIT: baseurl is a Javascript variable, right now it is http://localhost/test/ but it will be changing, which is why I want to use a variable.

EDIT 2: It was a path problem, thank you guys for the answers

+2  A: 

It will take the url from the location of the file in which it is applied, so if your page is http://mysite.com/index.html, it will be looking at http://mysite.com/images/bw.jpg

Try making your baseurl absolute by putting a slash at the start, or use a full URL

baseurl = "/mySubFolder";
baseurl = "http://mysite.com/mySubFolder";
nickf
Nit-picking, but for his example, a trailing forwardslash would be necessary. +1 anyway :)
Stuart Branham
+1  A: 

Question 1: jQuery will be setting the css of the background image to 'url(images/bw.jpg)' in exactly the same way as if you changed the css directly. In other words, if it's in a css file, it'll be relative to that css file. If it's inline, it'll be relative to the page.

Question 2: Have a look at nickf's answer - the only reason that wouldn't be working is that it's not the right path.

EDIT: Try examining the contents of the baseurl variable (firebug or even alert()). I can't see why that wouldn't work unless the path was pointing to the wrong spot.

Damovisa
A: 

You can also try:

$("#colorimage").css('background-url','url(' +  baseurl + 'images/bw.jpg)');
Darryl Hein