How to Show Alternate Image If Source Image Is Not Found? (Onerror Working in Ie But Not in Mozilla)

Display alternate image

You can do this using the CSS background-image property of the img element, i.e.


However, you have to give a width or height for this to work (when the img-src is not found):


Firefox onerror would not fire even when image is not valid

It is not a broken link.

The actually returns an image with the name of the url you requested.

just click your link to the image. It is not text what you are seeing, it is an image.


Here is some code that works in all browsers.

It does some basic feature detection.

function handle( elem, img, state )
if ((typeof(elem.onerror) === 'function' && state === 'fail')
|| (elem.width === 0)
elem.src = img;

It uses both onload and onerror, but requires a function defined in javascript to handle the situation.

Inputting a default image in case the src attribute of an html <img> is not valid?

You asked for an HTML only solution...

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"   "">
<html lang="en">
<head> <title>Object Test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<p> <object data="" type="image/png"> <img src="" alt="Stack Overflow logo and icons and such"> </object> </p>

img.onerror does not seem to work for IE8

Could it be that the page is already loaded by the time the img.onerror handler is executed, and IE doesn't rexecute the function for the dojo.addOnLoad(warningDialogFunc)?

Try changing

img.onerror = function() {

to simply:

img.onerror = function() {

How to silently hide Image not found icon when src source image is not found

You can use the onerror event in JavaScript to act when an image fails to load:

var img = document.getElementById("myImg");
img.onerror = function () { = "none";

In jQuery (since you asked):

$("#myImg").error(function () { 

Or for all images:

$("img").error(function () { 
// or $(this).css({visibility:"hidden"});

You should use visibility: hidden instead of .hide() if hiding the images might change the layout. Many sites on the web use a default "no image" image instead, pointing the src attribute to that image when the specified image location is unavailable.

How does one use the onerror attribute of an img element

This works:

<img src="invalid_link"

Live demo:

As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;.

If image isn't avaiable display image placeholder

edit simple line, this will place image if image is empty (not there). replace src attribute with this one

   src="'.(!empty( $cardata["PictureRefs"]))?(explode(',', $cardata["PictureRefs"])[0]):'img/placeholder.jpg' .'"

where your path to img is


change it to your placeholder path

Related Topics

Leave a reply