I am creating a div within a forEach loop to hold images (every image has its own div). The images are held in a separate folder 'media'. By setting the url of background-image in the way I have in the code below, I can access a single image, so all divs are populated with the same image.
Is there a way to populate each created div with a separate image, via the url? There are the same number of created divs as there are images in the media file.
$('.my-media').html('');
media.forEach(function (mediaItem) {
var div = $('<div>');
$(div).addClass("class-a");
$(div).addClass("class-b");
$(div).css('background-image', 'url(media/0.jpg)');
$(".my-media").append(div)
});
}
**Update - I have changed the code to this:
$('.my-media').html('');
media.forEach(function (mediaItem) {
var div = $('<div>');
$(div).addClass("class-a");
$(div).addClass("class-b");
for (let i=0; i < mediaItemIndex.length; i++){
$(div).css('background-image', `url('media/${mediaItemIndex[i]}.jpg')`);
}
$(".my-media").append(div)
});
}
where
``` var mediaItemIndex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
but this is now only displaying the final image for all the divs. Again, any and all help/ suggestions would be appreciated.
FINAL UPDATE: I've solved the issue.
The path file to the images was stored in an array of objects under 'media_url'. By using .replace("../",""), I got rid of the unnecessary part of the file path and could access the images.
The way I was initially trying to access the images was failing as it was creating a loop within a loop. The forEach loop was looping through the images already, so when I used for(let i =0;... I was creating an infinite loop that only displayed the final image.
Replacing this line $(div).css('background-image', 'url(media/0.jpg)');
with this line from my first edit
$(div).css('background-image', `url(${mediaItem.media_url.replace("../","")})`);
means that every image only displays once - i.e. problem solved.
Thanks everyone for your suggestions!