Fix Broken Images with jQuery Broken Image Fixer

Fix broken Image

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();

jQuery Broken Image Fixer
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.

Source

Advertisement


Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

1 Comments

  • Neeta mishra says:

    This is simple but excellent way. I not sure why this didn’t hit my mind. 😛

  • Raunak mahajan says:

    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.

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.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker