How to stop broken images showing

Viewed 24239

I have a table with some images that I want to start out with no images in them.I have set the src="".But when viewed in a browser it shows broken image pics.

<tr>
<td><img src=""> </td>
<td><img src=""> </td>
<td><img src=""></td>
</tr>

How can I prevent the browser from showing the broken image pics or X or whatever until I put some data into the src attribute.

13 Answers

If you're using Semantic UI React you can pass the img element to onError through the event's target property:

<Image src={imageObject.Url} onError={i => i.target.src=''} />

If you just want to get rid of broken image icon & don't want to hide the image and want to keep the resolution of it as is; Use a transparent base-64 image, to replace it.

Jquery:

$("img").on("error", function() {
    $(this).attr('src' ,'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
});

Pros:

  • No need to hide the image
  • No need to change Alt text of the image
  • base-64 image don't have specific height-width
  • works with jquery zoom (jquery.zoom.js), if the zoomed image is broken

I would just build on what others have provided by adding a placeholder or fallback image when the primary source is invalid. That way, you're guaranteed to return SOMETHING useful to the user. This is especially helpful when the source is service-driven or RESTful.

Source: missing-images-on-website

<img
    src="<%- data.primaryImage.url %>"
    alt="image description"
    onerror="this.onerror=null; this.src='unavailable.png';"
/>
Related