How to fix broken images automatically in jQuery?


In this tutorial, we will learn to fix broken images automatically in jQuery. Have you ever seen broken images while wondering on any website which shows only alternative text with the default icon of the broken image? Don’t you think it is a bad user experience? Obviously, it is.

So, when you develop the application or website, you should write some JavaScript or jQuery code such that it can automatically replace broken images.

Here, we will learn 2 to 3 different methods to fix broken images automatically using jQuery.

Use the ‘onerror’ event inside the HTML ‘ <img> ’ tag

We can use the events with the HTML tags. The ‘onerror’ event triggers when any error occurs for the HTML element. In our case, if the image URL is broken, it will trigger an onerror event, and we can set a new URL for the broken images.

Users should follow the below syntax to fix broken images automatically using the onerror event in jQuery.

Syntax

// image with the source URL
<imgsrc = "<Image URL>"onerror = "solveError(this);"/>
<script>
   function solveError(currentImage) {
      currentImage.src = "<New Image URL>";
   }
</script>

In the above syntax, we call the ‘solveError()’ function when an error occurs in the image URL. The function will fix the broken URL of the image.

Example

We have created the two image elements in the example below using the HTML ‘ <img> ’ tag. Both image elements contain the source URL, but the source URL is broken in the second image. Also, we have added the onerror event for both image elements.

When an error occurs inside the <img> tag, it will call the ‘solveError()’ function, and we have passed the reference of current elements as a parameter of the function. Inside the solveError() function, we are changing the value of the ‘src’ attribute for the reference image received in the parameter.

<html> <head> <style> img { width: 100px; height: 100px; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> </head> <body> <h2> Fixing the Broken image automatically using <i> jQuery each() method. </i> </h2> <img src = "https://www.tutorialspoint.com/static/images/logo-footer-b.png" /> <img src = "https://wwwS/images/logo-footer-b.png" /> <script> $("img").each(function () { if ( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) || this.readyState == "uninitialized" ) { $(this).attr( "src", "https://yt3.ggpht.com/ytc/AMLnZu8XtlipNIpeKZgTSg1z64NO-mF7FEmlC2qML8WvwA=s900-c-k-c0x00ffffff-no-rj" ); } }); </script> </body> </html>

In the above output, users can see that the first image is the original image, and as the second image is broken, it shows the replacement image.

Use .on() method of jQuery to automatically fix broken image

We can call the ‘.on()’ method for any HTML element inside jQuery. Basically, the on() method is used to detect single or multiple events on the reference element.

Users can follow the syntax below to detect errors for the image element using the on() method.

Syntax

$("img").on("error", function () {
   // code to change the URL of a broken image
   $(this).attr("src","https://yt3.ggpht.com/ytc/AMLnZu8XtlipNIpeKZgTSg1z64NO-mF7FEmlC2qML8WvwA=s900-c-k-c0x00ffffff-no-rj"
   );
});

We have called the on() method on every ‘ <img> ’ element in the above syntax. Also, we have called the callback function to replace the broken image URLs, when an error occurs on the image.

Parameters

The ‘saveAs’ function takes two parameters.

  • img − It is a selector. Users can keep it as it is to fix all broken images. Also, users can set the id or class of the images for which they need to trigger a particular event.

  • Error − It is an event name. It will detect “error” for selected images.

  • function() { } − It is a function that will execute when any error occurs for the selected image.

Example

There are two image elements have been created in the example below. One with the original URL and one with the broken image.

Inside jQuery, we have used the on() method to detect the error on every image and call the callback function when an error occurs. The callback function replaces the URL of the referenced image in which the error occurred.

<html> <head> <style> img { width: 100px; height: 100px; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> </head> <body> <h2> Fixing the Broken image automatically using <i> jQuery on() method. </i> </h2> <img src = "https://www.tutorialspoint.com/static/images/logo-footer-b.png" /> <img src = "https://wwwS/images/logo-footer-b.png" /> <script> $("img").on("error", function () { $(this).attr( "src", "https://yt3.ggpht.com/ytc/AMLnZu8XtlipNIpeKZgTSg1z64NO-mF7FEmlC2qML8WvwA=s900-c-k-c0x00ffffff-no-rj" ); }); </script> </body> </html>

Use .each() method of jQuery to automatically fix broken image

In this method, we have used each() method of jQuery to iterate through all selected images. We will check for the original width of every image. If the original width of any image is 0 or undefined, we can say that the image URL is broken, and we can replace it.

Users should follow the syntax below to iterate through every selected image and check for the broken image URL.

Syntax

// iterate through every image element
$("img").each(function () {

   // check if the original width of the image is zero or undefined, then replace the image URL
   if (
      (typeof this.naturalWidth != "undefined" &&
      this.naturalWidth == 0) ||
      this.readyState == "uninitialized"
   ){
       $(this).attr("src","https://yt3.ggpht.com/ytc/AMLnZu8XtlipNIpeKZgTSg1z64NO-mF7FEmlC2qML8WvwA=s900-c-k-c0x00ffffff-no-rj");
   }
});

In the above syntax, we check the type of natural width of the image, the natural width itself, and the ready state of the image according to its values replacing the broken image URL.

Properties

  • typeof − It returns the type of the variable or any property.

  • naturalWidth − It returns the original width of the image. Even if the user changes the image's width, it returns the original width.

  • readyState − It returns the Boolean value according to whether the image is loaded into the document.

Example

The below example demonstrates to fix broken images automatically by iterating through every image using each() method of jQuery. It simply uses the attr() method of jQuery to replace the value of the ‘src’ attribute for every broken image.

<html> <head> <style> img { width: 100px; height: 100px; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> </head> <body> <h2> Fixing the Broken image automatically using <i> jQuery each() method. </i> </h2> <img src = "https://www.tutorialspoint.com/static/images/logo-footer-b.png" /> <img src = "https://wwwS/images/logo-footer-b.png" /> <script> $("img").each(function () { if ( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) || this.readyState == "uninitialized" ) { $(this).attr( "src", "https://yt3.ggpht.com/ytc/AMLnZu8XtlipNIpeKZgTSg1z64NO-mF7FEmlC2qML8WvwA=s900-c-k-c0x00ffffff-no-rj" ); } }); </script> </body> </html>

In this tutorial, we have learned three different methods to replace broken images using jQuery. Also, users can use the hide() method to hide the broken image in jQuery.

It is recommended to use the first method as it is the simplest one, and users can use other methods according to requirements.

Updated on: 21-Nov-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements