Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript to replace broken images

I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.

How do I use jQuery to get the set of images, filter it to broken images then replace the src?


--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.

like image 353
Dan Lord Avatar asked Sep 18 '08 13:09

Dan Lord


People also ask

How to check broken image in JavaScript?

To check if an image is not completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can combine this with the naturalWidth or naturalHeight properties, which would have a value of 0 when the image fails to load.

How do you show an alternate image if source image is not found?

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.


2 Answers

Handle the onError event for the image to reassign its source using JavaScript:

function imgError(image) {     image.onerror = "";     image.src = "/images/noimage.gif";     return true; } 
<img src="image.png" onerror="imgError(this);"/> 

Or without a JavaScript function:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" /> 

The following compatibility table lists the browsers that support the error facility:

http://www.quirksmode.org/dom/events/error.html

like image 76
Prestaul Avatar answered Sep 23 '22 13:09

Prestaul


I use the built in error handler:

$("img").error(function () {     $(this).unbind("error").attr("src", "broken.gif"); }); 

Edit: The error() method is deprecated in jquery 1.8 and higher. Instead, you should use .on("error") instead:

$("img").on("error", function () {     $(this).attr("src", "broken.gif"); }); 
like image 27
travis Avatar answered Sep 22 '22 13:09

travis