How to replace broken images with JQuery?
This morning, I found a very useful JQuery tip posted by StackOverflow's member Prestaul.
Thanks to him, I discovered that some browsers expose an onerror event on the image tag! The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).
This is a great solution to replace broken images when they are not hosted on your own website.
Here is a working example:
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
Thanks to him, I discovered that some browsers expose an onerror event on the image tag! The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).
This is a great solution to replace broken images when they are not hosted on your own website.
Here is a working example:
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