Fix Broken Images with jQuery Broken Image Fixer

If you usually add images from third-party websites via direct links, you may face the broken image problems. Suppose that website removed the image. Now, it will show broken image on your website. Broken images look dirty and also affect the look and feel of your website. It is also not good for the user experience of your website. So, there should be a solution for this. You can use jQuery to fix broken images and show a message container in place of broken image.
Process is simple. You need to find all image elements on the page and check if the image is valid. If the image is invalid, you can replace that image with a default placeholder image.
See the jQuery code below:
function brokenImages() { var totalimg = $("body").find("img").length; var brokenimg = 0; $('img').each(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { brokenimg ++; this.src = 'http://i.imgur.com/nIrhl0z.png'; //image which you want to show in place of broken image } }); } brokenImages();
See this snapshot. In place of broken image, it is showing broken image container. You can use the above code in your website. Just put the above code in the footer of your website.
You can change the broken image container image in the code above. Use any image which you want to show in place of broken image.
Similar Articles
1 Comments
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.
This is simple but excellent way. I not sure why this didn’t hit my mind. 😛
This is awesome. I faced the broken image issue when I moved my website from blogger to WordPress but accidentally deleted the album from Google account. Using this is better than showing broken images to visitors.
Thanks for this awesome article.