Adding img tag to div - and not it's not how to use append()

I correctly add an img tag with the following code but it only displays as a little box with an X in it on the webpage. To test I added this same img tag right in the webpage. That displays fine. I looked at both img tags in developer tools (PF12), and the tags on the page are the same. What I figure is happening is that in jQuery I'm loading the image tag after all the http requests for content have been scheduled, so I'm getting the tag, but it's too late in the browser's processing to get the source file requested and loaded. I'm trying to load different images on first display of the page (depending on contents of a hidden input field - accessing this and deciding which image is working fine based on a few alerts I've inserted).

Here's the code inserting the image (with the decisioning removed while I work out this problem):

$(document).ready (function() {
            $('<img class="rcpt" src="~/Images/MountainCrs_Incline.png" alt="" />').appendTo('div#Logo');
});

Here's the inserted img tag which only displays the "unresolved reference" box (copied right from the resulting html):

<div id="Logo"><img class="rcpt" alt="" src="~/Images/ChampCrs_Incline.png"></div>

Here's the img tag I inserted into the native html to verify the img tag is formatted correctly (this one displays fine):

<h3>&nbsp;</h3>
<img class="rcpt" alt="" src="/Images/ChampCrs_Incline.png">
<h3>&nbsp;</h3>

If anyone could tell me what's going on and how to fix it I'd much appreciate it. I'm using Visual Studio 11 and IE10 for my testing. Thankx...

Upvotes: 0

Views: 457

Answers (3)

palaѕн
palaѕн

Reputation: 73966

Try this using ResolveClientUrl:

var url = '<%= ResolveClientUrl("~/Images/MountainCrs_Incline.png") %>';
$('<img class="rcpt" src="' + url + '" alt="" />').appendTo('div#Logo');

Upvotes: 1

Gavin
Gavin

Reputation: 7976

You have a tilde (~) in the src property of the img tag you're inserting with jQuery, but not in the "native html" markup. A tilde is a valid URL character. I'm assuming you're using .NET. Using tildes in URLs the way you are only works server side.

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68440

This is not a valid client url

~/Images/MountainCrs_Incline.png

That's resolved on server side to a valid url but on client side make no sense. Try replacing that by

/Images/MountainCrs_Incline.png

Upvotes: 4

Related Questions