Implementing global event callback in JavaScript

Is there a way to globally add an `onerror` function for the `div.circle_thumb>img` event?

Instead of adding an `onerror` event to each img tag individually, such as shown below.

<div class="circle_thumb" ><img src="some/url" onerror="this.src=url/to/replaced" /></div>

I find this method to be quite bothersome. Is there a more efficient way to handle this?

Answer №1

If you want to manipulate images with JavaScript, here's an example you can follow:

[].forEach.call(document.querySelectorAll('div.circle_thumb>img'), function(img) {
    img.addEventListener('error', function(e) {
    this.src='../img/logo.png';
  });
});

Alternatively, you can use ES2015+ syntax:

Array.from(document.querySelectorAll('div.circle_thumb>img')).forEach(img => img.addEventListener('error', e => img.src='../img/logo.png'));

Answer №2

Latest jQuery Version:

jQuery.each($('div.circle_thumb > img'), function(index, img){
    img.addEventListener('error', function(event) {
        img.src='../img/logo.png';
    });
});

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 maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

Embed programming into an iframe upon its loading

I am looking to enhance the functionality of an iframe by injecting HTML and JavaScript code into it upon loading. The goal is to enable users to navigate through different links within the iframe while they are browsing. Here is what I have attempted so ...

Retrieve data from an online JSON file

I am still learning about working with json and would appreciate some guidance. The data file I need to access is located at this url - I would like to display it in the following format: <ul id="smenu"> <li></li> </ul> Cou ...

What is the process for setting up URL parameters in Express JS?

I am working on creating an URL that can accept a query after the "?" operator. The desired format for the URL is "/search?q=". I am wondering how I can achieve this in Express JS, and also how I can integrate the "&" operator into it. ...

Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popu ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

What is the best way to eliminate the border of an expansion panel in Material-UI?

Is there a way to eliminate the border surrounding the expansion panel in Material-UI? ...

Tips for clearing object values without deleting the keys: Resetting the values of an object and its

Upon creating a service to share data among multiple components, it became necessary to reset the object values once the process was complete. To achieve this, I attempted the following: this.UserDetails = {}; This successfully cleared the values and remov ...

Unexpected behavior when using JQuery's .load() method

In my HTML code, I have a main div element with child elements as lists. These lists are dynamically populated with data from the server and each item in the list has a checkbox. When a checkbox is checked, I want that item to move to the bottom of the lis ...

Whenever I select a link on a navigation bar, it transports me to the desired section of the page. However, I often find that the navbar ends up

Recently, I came across some website templates where clicking on a link in the navbar smoothly scrolls to the corresponding section with perfect alignment. The content at the top of the page aligns perfectly with the top of each division. Upon attempting ...

Access denied encountered while executing NPM module that modifies environment variables in Nodejs on Kubuntu 18.04

While utilizing the npm module env-cmd to set environment variables on process.env in nodejs, I encountered a persistent "permission denied" issue on my Kubuntu 18.04 system. Even with sudo, I was unable to bypass the permission denial. My node and npm v ...

I'm feeling a bit lost on how to bring my random quote generator to life

I'm attempting to add animation to my random quote generator by making it look like another card is being flipped on top of the existing one, similar to a deck of cards. With limited coding knowledge, I followed a tutorial and made some adjustments to ...

Create a boolean flag in Java using JavaScript

Hey there, I'm working on a project where I need to detect the user's browser in JavaScript. For Safari browsers, I have to download an audio file, while for every other browser I need to play the audio. Currently, my code can correctly identify ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

Differentiating categories in the second parameter for controller method in AngularJS?

As a newcomer to Angular, I have noticed that the locals argument in the controller function can sometimes be just a function and other times an array. angular.module('contentful').controller( 'FormWidgetsController', ['$s ...

What is the purpose of using JSON.parse(decodeURIComponent(staticString))?

A specific approach is utilized by some dynamic web frameworks in the following code snippet <script> appSettings = JSON.parse( decodeURIComponent( "%7B%22setting1%22%3A%22foo%22%2C%22setting2%22%3A123%7D")); </script> Is there a part ...

Step-by-step guide on generating an index through mongoose and elastic search in a node.js and express.js environment

I am looking to set up the index in elastic search using mongoose and express, but I have not been able to find any documentation on how to do it. I attempted to use mongoosastic, but it did not meet my needs. Is there anyone who can assist me with this? ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

extracting data from json using javascript

Here is the data in JSON format var testData = {text: '{"status":200}'}; I am attempting to extract the status using this code: console.log(testData.text.status); However, it returns undefined Could you please provide guidance on how to succ ...