Reputation: 3314
I'm using jQuery to load page content like so:
$("#content").load(path);
Where the content files are purely content like such:
<!--page.php-->
I am content
However, when I want to include images in my content like this:
<!--page.php-->
<img src="images/image.jpg"/>
The path only works relative to the origin of the jQuery script instead of the page.php file, so the following example would not work with the code above:
Directory tree:
index.php
jQuery.js
pages/
page.php
images/
image.jpg
Because it's making page.php relative where the jQuery is, at the root of the site so it can't find the images folder unless I give it an exact path which in my actual site changes all the time depending on where the content file is located.
Is there a non-hacky way around this that doesn't involve me putting the exact path in every image or content I want to reference?
Upvotes: 2
Views: 1345
Reputation: 9658
Use attr('src') not prop because prop can add a base url to the relative path.
$(this).find('img').each(function () {
$(this).attr('src', address + $(this).attr('src'))
});
Upvotes: 0
Reputation: 153
You can set one global variable for the path of your image directory. and use that variable for path, wherever you put images.
If your path changes, you need to change only one variable value.
Upvotes: 0
Reputation: 6025
I know you said non hacky but you could do this after loading in the content
$("#content").load(path + '/page.php');
and then
$('#content img').each(function(){
$(this).prop('src', path + '/' + $(this).prop('src'))
})
Upvotes: 1