Handle broken image URL on our web page in jQuery

We generally show images on the web page using HTML¬†img tag. In the HTML image tag, we have to pass the image URL into the “src” attribute.

But when the image on that URL is no more exists, then it will show error. Depending on the browser, you can see various types of icon. Browsers represent the broken image with their icons so that we can understand that the image path doesn’t exist.

But the default broken image icon on the browser may not be cool enough for many of us. So, in this article, I am giving you a solution to make it cool by teaching you how to handle broken image URL in jQuery.

Here, I will show you the jQuery JavaScript code, that will replace the broken image icon with your own defined image. It will replace the icon with the image that you want and think to look cool.

 



Also, read:

 

Suppose, below is our HTML code to show an image on the web page:

<img src=”https://www.domain.com/img/my-image.jpg” />

Now, think that the image is no more available on that URL. Off course, in reality also there is no image available on “https://www.domain.com/img/my-image.jpg”. So now, it will show the image error icon of the browser. This is called a broken image and we are going to handle our broken image URL on the web page.

Below is how broken image looks on Chrome browser:

Chrome Broken Image Icon

 

jQuery JavaScript code snippet to handle broken image

Now we want to replace the icon with our favorite image. Below is the jQuery code that will replace each and every broken image on the web page into the image of our defined path:

$('img').on("error", function() { // Detect if there is an image loading error
  $(this).attr('src', 'default.jpg'); // Set a default image path that will replace image error icon
});

In the above jQuery JavaScript code, first of all, we are detecting if there are any error occur during loading the image. If there is an error occur or detected the image is broken, then we change the image “src” attribute value with the image that we want to replace the broken image.

Now if we run our code and the image is broken or there is no image exist to that path that we defined in our HTML image “src” attribute then it will run the JavaScript code that will change the image “src” attribute value and we will see that image instead of the broken image.

But, if we provide a valid image URL or path where the image exists, then it will show the image from the path that we defined in the HTML that we see normally.

I hope, you got the solution to handle broken images on the web page.

 

Leave a Reply

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