I have a website that includes code:
<html>
<head>
</head>
<body>
<div id="wrap">
<img id="img_1" src="images/sample.gif" alt="Image 1" width="200" height="40" />
</div>
</body>
</html>
I have this JavaScript and jQuery:
$(document).ready(function(){
$('#wrap').append('<img id="img_2" src="images/sample_2.gif" alt="Image 2" width="200" height="40" />');
alert($('#img_1').attr('src'));
alert($('#img_2').attr('src'));
});
In IE7,
the first alert displays: 'images/sample.gif'
the second alert displays: 'http://hostname/images/sample_2.gif'
Is there a work around for this?
What I'm doing is bringing in a header from a website on a different server through JSONP and appending it to the current page. The header includes relative paths for some img tags, so I want to selectively check if they are indeed relative and prepend the remote servers hostname so they correctly display.
The function works for every browser but IE7 because of this issue.
--
After doing some more work. I have this JavaScript:
<script type="text/javascript">
$(document).ready(function(){
function Config(){}
Config.Framework = {
RemoteRoot: "http://remote-root.com/",
RemoteHostName: "remote-root.com",
LocalHostName: window.location.hostname
};
$('#wrap').append('<img id="img_2" src="images/logo.gif" alt="Logo" width="100" height="93" />');
$('#wrap').append('<img id="img_3" alt="Logo" width="100" height="93" />');
$('#img_3').attr("src", "images/logo.gif");
$('img', '#wrap').each(function(i){
set_src($(this));
alert(i + ': ' + $(this).attr('src'))
});
function set_src(img) {
var src = img.attr('src');
if ($.inArray(Config.Framework.LocalHostName, src) > -1) {
img.attr('src', src.replace(Config.Framework.LocalHostName, Config.Framework.RemoteHostName));
} else {
img.attr('src', Config.Framework.RemoteRoot + src);
}
}
});
</script>
So the set_src function checks if the local hostname is in the src string, if it is, I replace it with the remote hostname. This is fine if the page that pulls in the image is at the root folder. But many times it is not.
If the image is pulled into a page that is not in the root directory, it will set the src as (only in IE7):
If in root directory it does:
Original: 'http://local-hostname.com/images/logo.gif'
After function: 'http://remote-root.com/images/logo.gif'
If outside root directory:
Original: 'http://local-hostname.com/path/to/page/images/logo.gif'
After function: 'http://remote-root.com/path/to/page/images/logo.gif'
What I need: 'http://remote-root.com/images/logo.gif'