Replace Broken Images With Default Image Using JavaScript OR jQuery OR HTML

Images are common in web pages now a days. These images make the web page attractive and beautiful. But sometimes due to problems, some images won't load completely. When the image doesn't load completely, that image is said to be a broken image. When the image is broken, the Browser will replace that broken image with an ugly image or replace the broken image with a blank space. I have included a broken image below. Different Browsers will render the broken image in different ways.
The replaced image by browsers look ugly and the page loses it's beauty.

What Causes a Broken Image ?

  1. Slow Internet Connection makes the image broken
  2. Image Does not exist (404)
  3. Image URL redirects to a non Image URL
  4. User stops the loading of the page.

Fix # 1

Using JavaScript,we can easily replace the image with a default image. In Fix # 1, we will add onerror attribute tothe image element :
<img src="http://subinsb.com/to-an-image" onerror="this.src='http://subinsb.com/path-to-default-image';"/>
If you have a lot of images and need to apply an onerror attribute on each of them, it's very difficult. If you want something like that, see Fix # 2.

Fix # 2

The following code will add an onerror function on all images of a web page. It's pure JavaScript.
(function(){
for(i=0;i<nodes.length;i++){
nodes[i].onerror=nodes[i].src='http://subinsb.com/path-to-default-image';
}
})();
If you really need to do the task in jQuery, see Fix # 3.

Fix # 3

The following jQuery code will do the same function as Fix # 2.
$(document).ready(function(){
$("img").each(function(){
$(this).attr("onerror","this.src='http://subinsb.com/path-to-default-image'");
});
});
In all of the fixes above, the path of the default image is :
http://subinsb.com/path-to-default-image

Comments

Popular posts from this blog

HOW TO REGISTER FOR SAFETOKEN

How To Get Help In MMM Nigeria - Mavrodi Mondial Moneybox