Reputation: 8497
I have a html5-document that contains this element:
<div id="imgContainer"></div>
The document loads, the user logs in, and some new text gets loaded and successfully displayed via Ajax (using jQuery). After a while (when the user makes a click) a new image should be inserted into the imgContainer
-div.
I do this with this jQuery-command:
$("#imgContainer").html('<img src="newImage.png" alt="">');
The file newImage.png
is located in the same directory as the html-file and the javaScript-file. But it does not appear in the browser-window. But it is correctly inserted into the source-code. I checked this with the developer-tools of my browser (safari). This tools don't report any error. But still the image is invisible. When I look into the list of resources I can see no newImage.png
. Obviously the browser didn't load it. But why?
The image appears in the browser-window when I enter its URL. So the browser is able to load it. But it does not when I modify the html-document. Why?
Must I add some additional code to ma javaScript to tell the browser to load the image? If so: Can you tell me this code?
Edit:
try here: http://jsfiddle.net/YCs66/1/
Upvotes: 1
Views: 535
Reputation: 2340
http://jsfiddle.net/dwebexperts/ZCL2U/1/
Replace this
$("#imgContainer").html('<img scr="https://www.google.com/textinputassistant/tia.png" alt="">');
with this
$("#imgContainer").html('<img src="https://www.google.com/textinputassistant/tia.png" alt="">');
As I checked in your Fiddle, you have given source attribute as "scr".
Upvotes: 4
Reputation: 721
The problem with your code is that the .html()
method only puts in the HTML without actually parsing the attributes for the DOM element
. Here is the solution
HTML
<form name="myForm" action="">
<input type="button" value="click me"
onclick="loadPic()">
</form>
<div id="imgContainer"></div>
Javascript
var loadPic = function () {
alert("loadPic started");
$("#imgContainer").html('<img/>');
$("img").attr("src", "https://www.google.com/textinputassistant/tia.png");
alert("loadPic finished");
};
Note that the <img/>
that is performing .attr("src", ...)
is an asynchronous
function. As a result, 2 alert()
s will come out before the actual image is being loaded.
Upvotes: 0