UPDATE: I'm still struggling with this issue.
I am attempting to dynamically set the src attribute for multiple img tags within a gallery using JavaScript. Each slide in the gallery contains img tags categorized as "before" and "after". The challenge arises when some pages have all 8 photos while others have fewer. If an image successfully loads (defined here as not receiving a 404 error), a .loaded class is added to the img, displaying a border. However, if a 404 error occurs, a .hidden class is added, setting display: hidden for the img element.
Current dilemma: Despite encountering error messages in the console stating "GET http://blablabla/Images/gallery/job1/before-1.jpg 404 (Not Found)", the .onerror event does not trigger, but the .onload event does. When inspecting the img tags that haven't loaded, they contain a valid src attribute even though the image at that path doesn't exist. Shouldn't this result in an error?
const loadImg = function(img, url) {
return new Promise((resolve, reject) => {
img.src = url;
img.onload = resolve(img);
img.onerror = reject(img);
});
};
const populateBeforeImgs = function() {
for (let i = 0; i < beforeImgs.length; i++) {
const img = beforeImgs[i];
const url = `Images/gallery/job${galleryIndex}/before-${i + 1}.jpg`;
loadImg(img, url)
.then((value) => {
value.classList.add("loaded");
})
.catch((error) => {
error.classList.add("hidden");
});
}
};
const populateAfterImgs = function() {
for (let i = 0; i < afterImgs.length; i++) {
const img = afterImgs[i];
const url = `Images/gallery/job${galleryIndex}/after-${i + 1}.jpg`;
loadImg(img, url)
.then((value) => {
value.classList.add("loaded");
})
.catch((error) => {
error.classList.add("hidden");
});
}
};