Placing multiple images in HTML at once using JavaScript
EDIT: Here's another problem: I cannot define each image Z-index
with a for loop.
function placeImage(x) {
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter = 1; counter <= x; counter++ ) {
var image = document.createElement("img");
image.src = "borboleta/Borboleta" + counter + ".png";
image.width = "195";
image.height = "390";
image.alt = "borboleta" + counter;
image.id = "imagem" + counter;
image.position = "relative";
image.style.zIndex = counter;
div.appendChild(image);
}
};
window.onload = function () {
placeImage(20);
};
<body>
<div id="div_wrapper">
<div id="div_header">
<h1>First Project</h1>
</div>
<div id="div_picture">
<div id="div_picture_left"></div>
<div id="div_picture_right"></div>
</div>
</div>
</body>
When inspecting FireBug, I get this:
Error: Image is damaged or truncated
source to share
It looks like your code is being executed before div
on the page. You shouldn't try to get a handle to a DOM element until it's fully loaded. You can define your function outside window.onload
, but keep your call within window.onload
, for example:
function placeImage(x)
{
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter=1;counter<=x;counter++) {
var imagem=document.createElement("img");
imagem.src="borboleta/Borboleta"+counter+".png";
div.appendChild(imagem);
}
}
window.onload = function() {
placeImage(48);
};
I also added a small improvement, which is to get a handle to div
and store in a variable once, instead of getting a new handle on each iteration.
source to share
Try the following:
var placeImage = function(x) {
var img="";
for (var counter = 1; counter <= x; counter++ ) {
img += '<img src="borboleta\Borboleta'+counter+'.png" alt="" />';
}
document.getElementById("div_picture_right").innerHTML = img;
};
placeImage(48);
With this code, there is only 1 DOM operation, not 48. Also make sure you have an element with the specified id (div_picture_right).
source to share