Set a default image for broken or Unavailable image URL in JavaScript

By Faruque Ahamed Mollick

When the URL of an image on the web page is no more available then the images can’t be seen also on the web page and on many of the browsers, it shows some kind of marking that doesn’t look good. These type of image called broken image.

A broken image often noticeable by the user. To increase better user experience we can prevent the ugly situation when the image URL is broken and it is no more available on web page. Using JavaScript we can easily set a default image for those broken images.



Locate the Geo-position of a visitor in JavaScript

Send AJAX request every n seconds using jQuery

Generally, we show images on the web page using the HTML img tag:

<img src="myPicture.img">

If “myPicture.img” path is no more available then it will become a broken image and we will not see any image on our web page. We can see a box marking which looks bad.

To prevent this, we are going to set a default image. We can do it just by using the code below:

<img onerror='this.src="broken_image.png"' src="myPicture.jpg"/>

The above code will show the image “broken_image.png” if “myPicture.jpg” is not available.

Set default image for broken image using jQuery

We can also set the default image for broken images using jQuery code:

$(document).ready(function(){
  $("img").bind("error",function(){
    // Set the default image
    $(this).attr("src","broken_image.png");
  });
});

Now we can see our own default image instead of the blank or boxed mark if the image URL not available.

Leave a Reply

Your email address will not be published. Required fields are marked *