Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML if image is not found

Tags:

html

People also ask

What if image is not showing in HTML?

Why Is My Image Not Showing up in HTML? One of the reasons why your HTML image not showing in browser is that its file is not located in the same folder that is indicated within your tag. Also, the image may not load because the file name specified in the <img> tag does not match that of your image file.

How do you code an image to display text if the image doesn't load?

The alt attribute is meant to be used as an alternative text if the image is not available. Text-only browsers cannot display images and will only display the text specified in the alt attribute.


The best way to solve your problem:

<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.src='Default.jpg'" alt="" width="100" height="120">

onerror is a good thing for you :)

Just change the image file name and try yourself.


Well you can try this.

  <object data="URL_to_preferred_image.png" type="image/png">
   <img src="URL_to_fallback_image.png" />
  </object>

this worked for me. let me know about you.


Ok but I like to use this way, so that whenever original image is not available you can load your default image that may be your favorite smiley or image saying Sorry ! Not Available, But in case if both the images are missing you can use text to display. where you can also you smiley then. have a look almost covers every case.

<img src="path_to_original_img/img.png"  alt="Sorry! Image not available at this time" 
       onError="this.onerror=null;this.src='<?=base_url()?>assets1/img/default.jpg';">

For the alternative, if the image doesn't exist - show nothing at all. (what I was looking for)

You can swap the function from Robby Shaw's answer in the "onerror" attribute to "this.remove()".

<img id="currentPhoto" src="SomeImage.jpg" alt='1' width="100" height="120">
<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.remove();" alt="2" width="100" height="120">

Here Check below code snippet which, In this, I miss-spelled the image name. So, just because of that it is showing the alternative image as not found image ( 404.svg ).

<img id="currentPhoto" src="https://www.ccrharrow.org/Images/content/953/741209.pg" onerror="this.src='https://www.unesale.com/ProductImages/Large/notfound.png'" alt="">