How to replace all broken images with jQuery/JavaScript?

I have a wallpaper website, where I have often found broken images. Images have permission errors like access denied or are removed from the source. So when a broken image is displayed in the browser it does not look good and brake my website design.

How can I trigger an event when an image failed to load, so I can replace the src of that image with a default image or a not found image?. Like I have a jquery “load” event. Or do I have to get all the images, filter broken images then replace the src?

You can achieve your goal with a very simple solution.

With JavaScript

<img src="image.png" onerror="this.onerror=null;this.src='/images/no-found.gif';" />

This will do the trick!

You can even attach a function to onerror attribute.

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

If you don’t want to edit your Html or want a jQuery solution

With jQuery

$("img").on("error", function () {
    $(this).attr("src", "/images/noimage.gif");
});