Reputation: 1779
I have following code:
<img src="test.jpg" width="20" height="20"> some content here
When image is not found, it shows like following:
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
Upvotes: 6
Views: 3730
Reputation: 20881
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.
Upvotes: 11
Reputation: 1522
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'"/>
Upvotes: 3
Reputation: 952
You need to use the backend programming to determine if the path exists and contains an image then display it. If the path does not exist or does not contain an image then you can decide to display a default image or any component of your choice.
In PHP you can do it as follows:
<?php
if (file_exists('test.jpg')) {
echo "<img src='test.jpg'>";
} else {
echo "<img src='default.jpg'>";
}
?>
Upvotes: 0