Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace HTML img broken by missing or erroring image src

I have following code:

<img src="test.jpg" width="20" height="20"> some content here

When image is not found, it shows like following:

enter image description here

This behavior is different according to browsers.

I want to display transparent box(plain white) or some good looking container(empty box) that will look same in all browsers. I have tried with alt tag, but it does not work.

How can I achieve this ?

Demo: Sample

<img src="img_girl.jpg" width="20" height="20"> some content here
like image 686
chirag Avatar asked Oct 30 '20 14:10

chirag


People also ask

How do I change the src of an image in HTML?

To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.

Can you change img src?

The required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.

Why IMG src is not working?

Img src Not Working That means, when a web page loads, the browser has to retrieve the image from a web server and display it on the page. The broken link icon means that the browser could not find the image. If you've just added the image, then check that you included the correct image URL in the source attribute.


Video Answer


2 Answers

You can use the error handler with onError. But make sure to cancel the onError handler after it is invoked, because if your backup-image is missing, this will cause an infinite loop of server requests -- not good! Handle it like this...

<img src="test.jpg" width="20" height="20" onerror="this.onerror=null;this.src='imageNotFound.gif';">

By setting this.onerror=null;, we are preventing an infinite loop of server requests. Then imageNotFound.gif will display for users if the image is there.

POD (Source: MDN Web Docs: GlobalEventHandlers.onerror)....

The reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error.

like image 144
HoldOffHunger Avatar answered Oct 28 '22 22:10

HoldOffHunger


Since you're using Angular you can simply use onError to show your fallback/error image in case that your initial src could not be loaded:

<img [src]="invalidPath" onError="this.src='images/angular.png'"/> 
like image 28
Entertain Avatar answered Oct 28 '22 20:10

Entertain