I have a site I’m trying to build where I want to load about 600 photos that all have a very similar file name Slide1, Slide 2, Slide3 etc.
I’m trying to figure out how to load the picture without having to call all 600 individually.
The original code I was trying to use was.
<div class="responsive">
<div class="gallery">
<a target="_blank" href="Slide1.jpg">
<img src="Slide1.jpg" alt="Forest" width="600" height="400">
</a>
</div>
</div>
I ended up changing it to
<div class="responsive">
<div class="gallery">
<div id="wrapper"></div>
</div>
</div>
So that I could use this script
<script>
var container = document.getElementById("wrapper");
var urls = 590;
for( i=1; i<urls; i++){
container.insertAdjacentHTML('beforeend', '<img src="/slides/Slide'+[i]+'.jpg" alt="/slides/Slide'+[i]+'.jpg">');
}
</script>
But I lose some of the original functionality. And I’m having some people tell me it breaks after Slide150 or Slide200
And I haven’t found a better way that actually works.
3
Answers
This way, you can set width, height and other properties too-
Try this. What I did is changed the way it adds it to the wrapper, and I added an end "/" to the img tag.
Let me know if this works! 🙂
Here is a very terse way of doing what you want:
The
.map()
expression is at the core of the functionality:.map()
loops over the arrayarr
For each iteration the callback function takes the current indexi
adds the value1
to it and places it into a URL-type string:baseURL+(1+i)+size
. The result of this string concatenation is stored into the variabev
(which initially simply holds the value0
) and then it is used to create a part of the resulting HTML string, which is put together by.join()
-ing it with an
between each image. On the page then
will appear as a simple white-space.The sample pictures for this snippet were taken from https://picsum.photos and, as you can see, not all picture positions are filled. In these positions you can see the
alt
string.My solution differs from the previous ones as it changes the HTML content of the page only once. This will make it much faster.