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
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.
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.
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.
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.
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'"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With