Basically my question is how can I do this? Anywhere I looked I couldn't find answers.
for(var i = 0; i < 4; i++){
var img = document.createElement("img");
img.style.src = img/${i}.png
;
if(img exists)
document.body.appendChild(img);
}
Also is this possible somehow?
for( i = 0; i < how many images are inside folder; i++)
Top comments (4)
You can add
onload
andonerror
event handlers to theimg
element you created.onload
can be used to add the image to the page, but the order would depend on the order the requests complete, so they may appear out of sequence.You could place them all on the page after setting
img.style.display = 'none';
and use the event handlers to remove the style inonload
or remove the element withonerror
.There are a couple of other ways you could go about this, but that is probably the simplest way to get started.
for(var i = 0; i < 4; i++){
}
in my folder i have 1.png 2.png 3.png but not 0.png and yet this code gives me 4 times asd, what am i doing wrong?
You are starting your loop with zero as the base value for
i
. The increment in the afterthought runs after each loop. If you don't want to include zero, you should start with1
.First guess would be to confirm that your src path is correct.