How to show an alternative image if the original image is not found? (onerror works in IE, but not in mozilla)

I need to show an alternate image in a table cell if the original image is not found. Currently, the code below is used for this.

cell.innerHTML="<img height=40 width=40 src='<%=request.getContextPath()%>/writeImage.htm' onError='ImgErrorVideo(this);'>" function ImgErrorVideo(source){ source.src = "video.png"; source.onerror = ""; return true; } 

Now the problem is that the solution above works in Internet Explorer, and not in Mozilla.

Please tell me some solution that works in all browsers.

+97
javascript html image
Oct 21 '10 at 4:30
source share
3 answers

I think it is very nice and short

 <img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" /> 

But be careful. The custom browser will be stuck in an infinite loop if the onerror object itself generates an error.




EDIT To avoid an infinite loop, immediately remove onerror .

 <img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" /> 

By calling this.onerror=null , it removes onerror and then tries to get an alternate image.




NEW I would like to add a jQuery way if this can help someone.

 <script> $(document).ready(function() { $(".backup_picture").on("error", function(){ $(this).attr('src', './images/nopicture.png'); }); }); </script> <img class='backup_picture' src='./images/nonexistent_image_file.png' /> 

You just need to add class = 'backup_picture' to any img tag that you want to load the backup image if it is trying to show a bad image.

+319
Mar 27 '12 at 13:57
source share

I have a solution for my request:

I did something like this:

 cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>" function setDefaultImage(source){ var badImg = new Image(); badImg.src = "video.png"; var cpyImg = new Image(); cpyImg.src = source.src; if(!cpyImg.width) { source.src = badImg.src; } } function onImgError(source){ source.src = "video.png"; source.onerror = ""; return true; } 

Thus, it works in all browsers.

Thanks Jyoti

+2
Oct 21 '10 at 9:40
source share

If you are open to a PHP solution:

 <td><img src='<?PHP $path1 = "path/to/your/image.jpg"; $path2 = "alternate/path/to/another/image.jpg"; echo file_exists($path1) ? $path1 : $path2; ?>' alt='' /> </td> 

//// EDIT OK, here's the JS version:

 <table><tr> <td><img src='' id='myImage' /></td> </tr></table> <script type='text/javascript'> document.getElementById('myImage').src = "newImage.png"; document.getElementById('myImage').onload = function() { alert("done"); } document.getElementById('myImage').onerror = function() { alert("Inserting alternate"); document.getElementById('myImage').src = "alternate.png"; } </script> 
+1
Oct 21 '10 at 4:50
source share



All Articles