Using an asynchronous JavaScript promise to dynamically change the source of an image

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");
            });
    }
};

Answer №1

Issue with the loadImg function:

if (Response.ok) {       

The problem lies in accessing Response.ok as it is undefined, which evaluates to false (a falsy value).

Consider modifying your code like this:

const loadImg = function(img, url) {
  return new Promise((resolve, reject) => {
    img.src = url;
    img.onload = () => resolve(img);
    img.onerror = () => reject(img);
  });
};

const img1 = new Image();
const img2 = new Image();

loadImg(img1, "https://www.placecage.com/c/200/300").then((img) => console.log("image 1 loaded!")).catch(() => console.warn("img 1 failed to load"));
loadImg(img2, "https://ihopethisisnotavalidurladasdasd").then((img) => console.log("image 2 loaded!")).catch(() => console.warn("img 2 failed to load"))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sharing content within an iframe

Despite my efforts to find a solution, I have been unable to come across one that aligns with my specific situation. I currently have a form for inputting person data. Within this form, there is an iframe containing another form for adding relatives' ...

What purpose does tagging serve in my template for polymer property binding?

I'm currently exploring the way Polymer handles the rendering of properties in a custom element's template. I've come across some interesting behavior that I haven't been able to fully grasp yet. Specifically, I noticed that certain pro ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Sending data from a bespoke server to components within NextJS

My custom server in NextJS is set up as outlined here for personalized routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname, query } = parsedUrl ...

Difficulty encountered in storing information in the database

I have been developing a survey generator but I am facing an issue where everything is empty. The client enters one or many questions, along with one or many answers for each question. These inputs are sent to my database. I have successfully coded the d ...

how to make a scroll event bubble in rxjs

When using vanilla JavaScript, I can easily catch any scroll event on any element by including true as the last argument: document.addEventListener('scroll', function(e) { console.log(e); }, true); However, with rxjs it's not as straight ...

JSplumb creates connections with several different endpoints simultaneously

I want to create lines from d1 to d2 and d1 to d3 using the JSplumb library. This code below only works with a single source and target point. JS: jsPlumb.ready(function(){ jsPlumb.Defaults.Endpoint = "Blank"; var container = document.getElementByI ...

tips for choosing an element using getByTestId that matches a particular value in react-testing-library

When working with React, I have a scenario where I am mapping out elements from an array. For instance: {options.map((option)=>{ return <div data-testid="option">{option}</div> }) In some cases, I need to select an option withou ...

Eliminating certain buttons within Ember-leaflet-draw

Is there a way to remove specific buttons from the UI in my Ember application that are used for drawing lines, circles, and polygons? I am currently using Leaflet Draw in my project. Here is a snippet of my template.hbs: {{#leaflet-map onLoad=(action &apo ...

Guide on How to Upload Huge Files Using a Single Connection in JavaScript

As I work on writing some HTML/JS code to enable the uploading of large files (multi-GB) to a remote server, I am facing some challenges. In the past, we relied on a flash uploader that sent a file in a single network request. However, using flash has now ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Enhancing the ShaderMaterial attribute in three.js

Exploring the three.js tutorial on shaders, we discover a technique for updating uniform values of a ShaderMaterial: var attributes = { displacement: { type: 'f', // a float value: [] // an empty array } }; var uniforms = { amplitu ...

If a single checkbox is selected within a group, then every other checkbox should be deactivated and deselected

Here is the code snippet provided: function listen(element, event, callback) { if (element.attachEvent) { element.attachEvent('on' + event, callback); } else { element.addEventListener(event, callback); } } var form = document.que ...

"Clicking the button will clear the values in the input fields

I have encountered a strange issue that I've never seen before. When I try to input the value of scope upon clicking on <a>, everything works fine. However, if I have entered values in other inputs and then click on <a> again, the values i ...

Navigating through the features of www.addthis.com is simple and straightforward

I am looking to integrate the addthis.com plugin into my website. Specifically, I want to pass my own data to the plugin when users click on the email link. This data should then be sent to the client. Is there a way to achieve this? ...

.Internet Explorer text update problem

Encountering a problem specifically in IE (like always). I've managed to narrow down the issue I'm facing to a recursive script responsible for updating a tweet's timestamp. The script functions correctly, identifying all the date/time sta ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

What is the best way to dynamically pass props to the styles hook in Material UI?

Looking for a way to dynamically add background images to div elements? I'm currently iterating over an array of objects and returning divs, but I'm not sure how to set the background image based on the image URL in each object. Can anyone help m ...

Implementing a versatile free text filter with numerous values using MUI

I am currently working on incorporating a free text filter view using MUI. Although the Autocomplete component already has this feature (when the 'multiple' attribute is enabled), I am looking to input free-form text instead of selecting from pre ...

The controller is frequently invoked, but specifically on Chrome for iOS

I am currently utilizing AngularJS to create a web application. Within my app, I am using $routeProvider for navigation. However, the app is quite complex, making it difficult to pinpoint the exact issue. I am curious if anyone else has encountered a simi ...