Enable error event listener only for the specified object

I am attempting to load a Youtube thumbnail using a URL. If the image from the URL does not exist or throws an error, I want to display a placeholder.

To achieve this functionality, I have written the following JavaScript code:

const yt = document.getElementById('YoutubeThumbnail'); //img tag of my requested image

yt.addEventListener('error', (){
    yt.setAttribute('src', 'placeholder');
});

This implementation works as expected, however, there is an issue where sometimes the favicon from the requested site also triggers an error. Just for reference, maxresdefault.jpg is the specific image I need to retrieve.

https://i.sstatic.net/H2JjJ.png

Since I am handling all errors in my code, it invokes the placeholder image when the favicon generates an error even if the requested image does not encounter any issues.

Is there a way to only handle errors related to my maxresdefault.jpg and ignore errors associated with the favicon?

Thank you for your help!

Answer №1

To enhance your anonymous error event handler, consider incorporating a parameter to analyze the value stored in the src attribute of the target element.

yt.addEventListener("error", (event){
    if(event.target.src === 'maxresdefault.jpg') {
        yt.setAttribute('src', 'placeholder');
    }
});

Answer №2

To achieve this, you can utilize the event.target.src property along with the includes function in the following way:

const yt = document.getElementById('YoutubeThumbnail'); // locating the img tag where the image is displayed

yt.addEventListener("error", (event){
    if(event.src.target.includes('maxresdefault.jpg'))
        yt.setAttribute('src', 'placeholder');
});

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

When text is wrapped within the <li> tag

In this div, the structure is as follows: <div class="box1" id="infobox"> <h2> Point characteristics: </h2> <div style="padding-left:30px" align="left"> <ul> <li class="infobox_list"><b>X value: </b>< ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Discover the secret to revealing hidden text as it seamlessly transitions through other text

I am working on a simple transition animation where I need to hide text (A href) initially using "display: none" and then make it visible with "display: block" after an image passes through it, triggered by a click event in JavaScript. Check out my code ...

Utilizing React Router for Notebook and Note Components with Nested Routes

I'm interested in developing a Notebook application that will allow users to organize their notes into different notebooks like "Mathematics" and "Science". The idea is to be able to select a specific notebook and view all the notes within that notebo ...

Incorporating a Vue application into a server-side framework application, encountering issues with Vue Public Path

Summary - Incorporating a Vue app into a Phoenix app. Constructing the Vue app with vue cli and ensuring the files are placed correctly within the Phoenix project directories. After building, there is an issue where the asset file paths do not align with t ...

Encountered a hard navigation error in NextJs when trying to navigate to the same URL while passing a query string

Currently, I am using NextJs version 13.0.2 and ReactJs version 18.2.0. My goal is to include a query string in the URL; however, I encounter the following error: Error: Invariant: attempted to hard navigate to the same URL /@workamirdanesh?w=true http://l ...

Contrast among 17-digit timestamps

Currently, I am dealing with timestamps in Node.js that are in the UTC+02:00 timezone. I am trying to calculate the time difference between two timestamps, each consisting of 17 digits. For instance, I have two timestamps: 20180712080000000 (YYYYMMDDHHmmss ...

Observing a two-way binding in AngularJS directive with the $watch functionality

I am currently working on differentiating between internal changes and external changes using a two-way data-bound attribute ('='). To clarify: I want to prevent $watch from triggering if the change was made internally (such as altering the scop ...

What causes TypeScript generics to infer varying types when an array member is enveloped?

I'm having trouble finding an answer to this potentially duplicate question, so please redirect me if it has already been addressed. My experience with generics in TypeScript has shown me that the inferred types can vary based on whether a generic is ...

What is the best way to utilize a variable across all functions and conditions within an asynchronous function in Node.js?

I need to access the values of k and error both inside and outside a function. Initially, I set k to 0 and error to an empty string, but unexpectedly, the console prints out "executed". var k = 0; var error = ""; const { teamname, event_name, inputcou ...

How can I display lowercase am/pm instead of uppercase AM/PM with angularjs date filtering?

Hi there, I'm a newcomer to AngularJS and I have a specific requirement. The server is sending me two dates: start_date and end_date. In the scenario where both dates are in 'pm', such as Sun 29 Jan 5.00 pm to Sun 29 Jan 6.00 pm, I would li ...

Step by step guide on how to get your hands on every aspect of

As I delved into three.js by referencing this documentation, I downloaded what I believed to be the complete library from here. However, as I encountered features such as OrbitControl and OBJLoader, they appeared to be missing from the downloaded three.j ...

Divergent behavior of SVG elements in Firefox versus Chrome with HTML5

I am trying to position a 'div' under a 'textarea' within an 'svg' and 'g' element. This works fine in Firefox, but not in Chrome. When I apply a transform on the 'g' element, it moves correctly to the des ...

steps to assign variables to $key and $value for ajax data

I am currently working on dynamically generating ajax data using $key and $value for a search query. With three dropdown menus, I aim to loop through each of them when one changes in order to retrieve their values and create a $key + $value pair for my aja ...

a collection of Interface objects

I've created an interface that looks like this: export interface testInterface { value1: string; value2: string[]; SubValue: [{}] } Everything works fine as I fill an array of type testInterface, which is bound to a dropdown list. Now, ...

Using JSON.stringify to format data and making an asynchronous $http request

I am working with a JavaScript string that looks like this: user_fav = "21,16"; I need to process this string through a function so that it becomes a JSON array with an id key, like this: {"id":21},{"id":16} This JSON array is then used in an $http req ...

Is there a way to retrieve the watch time of an HTML5 video using PHP without relying on external software?

<video id='myVideo' controls autoplay> <source src='a.mp4#t=00:00:00' type=video/mp4> </video> Is there a way to calculate the watch time of an HTML5 video using PHP and save it to a variable without the need for ...

Discover a keyword located within particular markers

let find_word="xyz" let el=document.getElementById("text"); let arr = el.innerHTML.split(" "); let newarr=[]; for (let i = 0; i < arr.length; i++) { if (arr[i] === find_word) { n ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

Arranging routes in node.js like a pro

const express = require('express'); const router = express.Router(); router.use(function(req, res, next){ console.log(req.user) if(!req.user){ res.redirect('/login'); }else{ res.locals.username = req.user.us ...