Handling multiple image errors in Javascript: Onerror handlers for images

Seeking a solution to establish multiple fallbacks for image loading in the event that the original image source encounters an exception.

If we have an image tag like <img id="art">, this JS code will set a fallback image src to album.jpg when the initial image cover.jpg results in an error:

var art = document.getElementById('art');

art.src = "cover.jpg";

art.onerror = () => {
    art.src = "album.jpg";
};

How can we activate an additional onerror handler to establish another fallback option if album.jpg is not found? For example, if the loading of cover.jpg fails, followed by the failure of album.jpg, how do we then set up another fallback to something like front.jpg and so forth?

Answer №1

If the src property is updated multiple times, the same onerror handler will be triggered repeatedly.

let pic = document.getElementById('pic');

let sources = ['image1.jpg', 'image2.jpg','image3.jpg', 'image4.png']

pic.src = sources.shift()

pic.onerror = e => {
  console.log(`Failed to load ${pic.src}`)
  if(sources.length) pic.src = sources.shift()
}
<img id="pic">

Answer №2

Avoid adding extra error handlers; one instance will handle every change to the src attribute.

However, be cautious as this could lead to an infinite loop if the image fails to load and triggers a repetitive change of the src to 'album.jpg'.

To prevent this endless cycle, you can check the current src value and adjust your logic flow accordingly. Detecting the last possible image can help break the chain of errors.

var art = document.getElementById('art');
art.onerror = e => {
  console.log(`${e.target.src} not found`);
  
  if (e.target.src.endsWith('/cover.jpg'))
    art.src = "album.jpg";
  else if (e.target.src.endsWith('/album.jpg'))
    console.log('Last image - ending loop');  
};

art.src = "cover.jpg";
<img id="art" />

If you have multiple fallback images, consider using an array or object to list them and iterate through them sequentially.

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

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

Bi-weekly Calendar Gathering

I am able to get my events sorted by day with the following code: daysOfWeek: [2], However, I have not been able to find any information in the documentation on how to make it sort fortnightly. Can this be done with fullcalendar? Solution: Just a heads ...

In Javascript, you can compare an array with a nested array and then store the values in a new array

Two arrays are at hand const arrayOne = [ {id: '110'}, {id: '202'}, {id: '259'} ]; const arrayTwo = [ {data: [{value: 'Alpha', id: '001'}]}, {data: [{value: 'Bravo', id: '202'}]}, ...

Is it possible to retrieve a list of controllers that are connected to an object in Three.js?

Is there a method in Three.js to retrieve the list of controllers linked to an object? Or perhaps just one controller linked to that object. I have connected a controller to an object, but I do not want the transformController to always be visible on it. E ...

When I submit a form with an empty date input field, the Datepicker is sending a 0000-00-00 date

[I am experiencing an issue with my date input field. When I submit without entering any value, the date on the view page shows as 0000-00-00 instead of being empty or blank.] <div class="col-sm-3 col-sm-offset-1"> <div class="input-group"& ...

What is the best way to extract raw data from a kendo dataSource?

After fetching data for my Kendo grid from the backend and populating it in the alignedProcessesToRiskGridOptions, I noticed that while the data is displayed in the grid, I also need access to the raw data for additional logic. Is there a way to retrieve d ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

The user input form in BotFramework V4 nodejs prompts the user again after submission

async feed_first(stepContext) { let company_card = MessageFactory.attachment( CardFactory.adaptiveCard(testfeedback) ); return await stepContext.prompt("textPrompt", { prompt: company_card }); } async feed_second(stepCon ...

Angular watch triggering even when the old and new values remain unchanged

function displayController($scope) { $scope.currentView = myCustomInstance.currentView; $scope.$watch($scope.currentView, function(newValue, oldValue) { console.log(newValue); cons ...

Is it possible to assign ng-model to multiple values simultaneously?

I am currently working on incorporating an input field into my project. <input type="text" ng-model="choice.text"> Using choice.text allows me to create a new text property within the object choice. This functionality enables me to send the input c ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

Add a hovering effect to images by applying the absolute positioning property

On my React website, I am utilizing Tailwind CSS and I am attempting to showcase an image that has interactive elements. I want certain parts of the image to increase in size slightly when hovered over. My approach to achieving this was to save each part o ...

Removing the "delete" button upon clicking within ng-repeat

When displaying data using ng-repeat, there is a button to delete each item. Upon deleting an item, the delete button should only disappear for the specific item that was deleted. <tr ng-repeat="paymentinfo in paymentList | filter:keyword | filter:mone ...

I have attempted to create custom code for the built-in JavaScript function (toLocaleUpperCase). Can this be considered helpful or not?

Using this JavaScript code snippet, you can convert lowercase letters to uppercase without relying on built-in functions. This is a helpful concept to understand for interviews and coding challenges. //change lower case to upper case function Change ...

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Tips for resolving the issue of "unable to load style sheet" in Bootstrap

I'm having trouble getting the grey color navbar to show up on my website. Instead, I keep getting a red error sign at the bottom saying "Stylesheet could not be loaded". I've tried removing one CSS file at a time, but nothing seems to be working ...

Using jasmine with Array.from is not a compatible combination

Attempting to utilize Jasmine for testing my code has presented a challenge. The code functions properly in the browser, and Array.from() also works seamlessly in node, as demonstrated below: > t = [1, 2, 3] [ 1, 2, 3 ] > Array.from(t) [ 1, 2, 3 ] ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...