Replace Broken Image With Some Default Image

Published On Thursday June 4, 2020 Reading Time: < 1 minute

Sometimes we can find some issues where some image has broken links, and it is really not a good idea to show the broken image to viewers. So here is a quick solution to these issue. We can overcome such difficulties with simple jquery snippets.

First, create a javascript function to replace the image

fixBrokenImages = function(url){
        var img = document.getElementsByTagName('img');
        var i=0, l=img.length;
            var t = img[i];
            if(t.naturalWidth === 0){
                //this image is broken
                t.src = url;

So, we need to call up the function in windows load

window.onload = function() {
        fixBrokenImages('default image url');

So, this is the quick solution to fixing the broken links of an image. The solution has been tested in chrome and firefox and its working well

Ref: Stackover Flow – Solution By Pim Jager

5 1 vote
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x