Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag:
If 1.jpg exists, show 1.jpg.
If not, check for 2.jpg and display it if it exists.
If neither 1.jpg nor 2.jpg exist, display 3.jpg.

<img src="1.jpg" onerror="this.src='2.jpg'; this.onerror='this.src=3.jpg'" />

An error occurred when trying this code. Is there another way to achieve this functionality?

Answer №1

Separate the handler into a JavaScript function:

function handleImageError(img) {
    img.onerror = function() {
        img.src = 'fallback.jpg';
    }
    img.src = 'main.jpg;
}

<img src="image.jpg" onerror="handleImageError(this)" />

Utilize the above function to create multiple cascading onerror handlers if needed. For longer sequences, consider storing images in an array and using the handler to increment an index with each call.

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

Enhance your React project by incorporating Material-UI card media elements with the ability to add

I am trying to figure out how to create an opaque colored overlay on top of an image using Material-UI. While it is possible with plain HTML, CSS, and JavaScript, I am facing some challenges with Material-UI. <Card> <CardMedia> <im ...

Express Node fails to launch

I recently decided to try my hand at Express and learn more about it. However, I encountered an issue while trying to start a server. Initially, I attempted to access 127.0.0.1:8080 through Express but nothing seemed to be happening. Although I copied most ...

Having difficulty displaying data in the proper format with two-way binding

In the realm of my webpage, I have a plethora of headings, paragraphs, images, and other data at my disposal. From the backend, a dataset is provided to me that includes an array with various properties housing the desired information. The challenge lies i ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

The process of uploading data onto a map using jquery is quite inconsistent in its functionality

HTML Instructions: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1"> <me ...

What is the process for assigning variables to modules using RequireJS?

Is there a way to define variables for modules in RequireJS? In simpler terms, how can I achieve the equivalent of the following using RequireJS: var fs = require('fs'); var child_process = require('child_process'); I am looking to s ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

Generate a table framework by dynamically adjusting the number of rows and columns

I'm running into an issue with my implementation of nested for-loops to dynamically generate a table using JavaScript. For this particular scenario, let's assume numRows = 2 and numCols = 6. This is the code snippet in question: let table = $( ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

When a parameter is passed into a React-Query function with an undefined value, it can lead to the API returning a 404 error

Two parameters are sent from the frontend to trigger a GET request in another TypeScript file. It seems that one of the parameters is not successfully passed due to unknown rerenders, resulting in a 404 Error being returned by the API call in the console. ...

Tips for testing components with React JS using jest and enzyme

Attempting to perform a unit test on the code snippet below: handleChange = (e) => { let localState = Object.assign({}, this.state) localState[e.target.name] = e.target.value this.setState(localState) this.props.addMetaInformation(localState) } } I&a ...

Using jQuery to reconstruct a list from a group of div elements

Seeking advice on how to convert an HTML section of divs into list items. Here is a sample of the current HTML structure: <div> <small>2019-10-31 10:41 Customer unregistered</small> </div> <div> <small>2019 ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Implementing time-limited class addition and removal using jQuery

Upon clicking an icon, a search box should appear. It will then automatically disappear after a certain interval of time (e.g., 5 seconds), even if the user clicks elsewhere on the page. $(".icon").click(function()){ $("search-box").addClass("active ...

What are the best techniques for effectively employing jQuery Deferred/promise in automatically invoked functions like .ajax()'s beforeSend()?

In my project, I am customizing jQuery's ajaxPrefilter to enhance the functionality of AJAX requests. Specifically, I am adding header data to the XHR request using setRequestHeader() within the beforeSend() method. The challenge I am facing is that b ...

What are the available choices for constructing HTML based on an ajax response?

Are there any alternatives or libraries available for constructing html from an ajax response? Currently, I am taking the json data received, creating the html as a string, and using a jQuery function to insert it into the DOM. However, I believe there mu ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

Learn how to efficiently pre-load data using the prefetchQuery method in React-Query

Attempting to pre-fetch data using react-query with prefetchQuery. The network tab in browser DevTools shows the requested data coming from the back-end, but strangely, the data is not present in the react-query DevTools cache. Any ideas on what might be c ...