jQuery/JavaScript to replace broken images
In case someone like me, tries to attach the error
event to a dynamic HTML img
tag, I'd like to point out that, there is a catch:
Apparently img
error events don't bubble in most browsers, contrary to what the standard says.
So, something like the following will not work:
$(document).on('error', 'img', function () { ... })
Hope this will be helpful to someone else. I wish I had seen this here in this thread. But, I didn't. So, I am adding it
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");
});
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