6

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

4

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for answer. its working as expected, I observed that it is not working in firefox browser. Is it something missing to add for firefox additionally ..??
@chirag Hrm, I'm not sure, but the documentation at MDN says that FireFox version 1.0 supported this, and, at the very bottom of the page, it summarizes support as "Full support". Not sure what could be happening, maybe cache? Are you inspecting and seeing the onerror call? What does the console log say? Any errors?
yes I am getting onerror call. but my this.src is not being called
3

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'"/> 

Comments

0

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'>";
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.