0

I am working on a site where i have arranged my pages in directories except for the index page. My problem occurs when i use jquery to append images to a div within a section of the pages. It shows on the index page but not on other pages (which are directories). I understand why but not sure how i can fix it.

Is there a way to fix this without having to remove my other files from directories?

var $img1 = $('<img src="images/test1.jpg" />');
var $img2 = $('<img src="images/test2.jpg" />');
$('#container').append($img1, $img2);

Please note that the above code is also in a separate directory

gables20
  • 496
  • 1
  • 7
  • 22

2 Answers2

2

Assuming that your images folder is located within the root directory of your website, you could just make the src attribute root-relative:

var $img1 = $('<img src="/images/test1.jpg" />');
var $img2 = $('<img src="/images/test2.jpg" />');
$('#container').append($img1, $img2);

(Note the / added to the beginning of the src attribute).

Reference:

Community
  • 1
  • 1
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • yes it is but i tried that before posting the question and it did not work. – gables20 Aug 07 '11 at 17:08
  • In what way did it 'not work'? It certainly ***should*** work. Is there any way you can provide a link to a demo site showing your attempts? Did you look at the console to see if there was a JavaScript error, or if the resources returned a 404 (or other) header? – David Thomas Aug 07 '11 at 17:12
  • there is no error. i have used firebug to inspect what is going on, and its simply is not loading the image. Perhaps, i should have pointed out that my js file is also in a sub-directory. – gables20 Aug 07 '11 at 17:14
  • It doesn't matter from where your JS is loaded, since the `src` will be relative (unless you use an absolute path, obviously) to the file/document in which they're loaded. – David Thomas Aug 07 '11 at 17:26
  • your actually right, that comment does not make much sense. however, i'm not sure just / would work for files in sub-directories. Dont you have to do something like ../ to get to a level higher? – gables20 Aug 07 '11 at 17:31
0

You can write the full link including domain name:
var $img1 = $('<img src="http://www.yoursitename.com/images/test1.jpg" />');

VIK
  • 689
  • 2
  • 9
  • 20
  • I know of the posibility to use absolute url but isn't there a way with relative path? – gables20 Aug 07 '11 at 17:09
  • @gables20: Yes, you can use relative path from the root as David said. But in the case if your site is hosted in subfolder of e.g. your organization's site ( e.g `http://organization.com/yoursite/`), you should take into account that `/` refers to `http://organization.com/`, not `http://organization.com/yoursite/`. Look at the `` html tag: http://www.w3.org/TR/html4/struct/links.html#h-12.4 – VIK Aug 07 '11 at 17:16